我有一个文本文件,其中包含以下内容:
0 12
1 15
2 6
3 4
4 3
5 6
6 12
7 8
8 8
9 9
10 13我想从data.txt文件中读取这些整数,并将这两列保存到Java语言中的两个不同的数组中。
我是Java的初学者,谢谢你的帮助。
发布于 2011-06-08 18:02:30
除非您事先知道文件中的行数,否则我建议您收集两个Lists中的行数,例如ArrayList<Integer>。
下面这样的代码应该能起到作用:
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
Scanner s = new Scanner(new FileReader("filename.txt"));
while (s.hasNext()) {
l1.add(s.nextInt());
l2.add(s.nextInt());
}
s.close();
System.out.println(l1); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(l2); // [12, 15, 6, 4, 3, 6, 12, 8, 8, 9, 13]如果您确实需要两个int[]数组中的数字,可以在以后创建这两个数组(当大小已知时)。
https://stackoverflow.com/questions/6277041
复制相似问题