读取包含两个整数列的TXT文件,并在java中保存为两个数组 [英] Read a TXT file containing two integer columns and save into two arrays in java
问题描述
我有一个包含以下内容的文本文件:
I have a text file containing the following content:
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中的两个不同的数组中。
I want to read these integers from data.txt file and save the two columns into two different arrays in Java.
我是Java的初学者,谢谢你的帮助。
I am a beginner in Java, and thank you for your help.
推荐答案
除非您事先知道文件中的行数,否则我建议您收集两个列表中的数字
,例如 ArrayList< ;整数>
。
Unless you know the number of lines in the file in advance, I suggest you collect the numbers in two Lists
, such as ArrayList<Integer>
.
这样的事情可以解决问题:
Something like this should do the trick:
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 []
数组中的数字,你可以在之后创建数组(当大小已知时)。
If you really need the numbers in two int[]
arrays you can create the arrays afterwards (when the size is known).
这篇关于读取包含两个整数列的TXT文件,并在java中保存为两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!