刚刚开始使用 Java 编程。如果我有一个存储在 .txt 文件中的数组,如下所示:
[10, 22, 30, 55, 10, 20, 19]
如何将其转换回正常的 int[] 数组以在代码中使用?
我需要能够将其简单地存储在这样的 txt 文件中,以便我可以手动对其进行更改。我使用 BufferedReader 来读取数组。如何将读取的数组放入 int[] 数组中?
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
String vals [] = line.split (",");
然后对于每个val
您可以使用
intVal [x] = Integer.valueOf (val[x].trim ());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)