将数组的字符串表示形式转换回Java中的int数组 [英] Convert string representation of array back to int array in java

查看:94
本文介绍了将数组的字符串表示形式转换回Java中的int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚开始使用Java进行编程.如果我将一个如下数组存储在.txt文件中:

just started programming with Java. If I have an array as follows stored in a .txt file:

[10, 22, 30, 55, 10, 20, 19]

如何将其转换回普通int []数组以在代码中使用?

How do I convert it back to a normal int[] array to be used within the code?

我需要能够将其清楚地存储在这样的txt文件中,以便我可以对其进行手动更改.我已经使用BufferedReader读取数组.如何将读取数组放入int []数组中?

I need to be able to store it plainly in a txt file like this so I can make changes to it manually. I've used BufferedReader to read the array. How can I put the read array into an int[] array?

int[] field;    
try {
    String line;
    br = new BufferedReader(new FileReader(gameFilePath));
    while((line = br.readLine()) != null) { // Read the first line and assume it is the stored array
        field = line;
        System.out.println("-------------------------------------------------------------------");
        System.out.println(line);
    }
} catch(IOException e) {
    e.printStackTrace(); 
}

推荐答案

因此,如果您的行是

[10, 22, 30, 55, 10, 20, 19]

那你就可以做

line = line.replace ("[", "");
line = line.replace ("]", "");

然后您可以使用String.split

then you can use String.split

String vals [] = line.split (",");

然后为每个可以使用的val

then for each val you can use

intVal [x] = Integer.valueOf (val[x].trim ());

这篇关于将数组的字符串表示形式转换回Java中的int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆