Read a TXT file containing two integer columns and store in 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

I want to read these integers from a data.txt file and save two columns to two different arrays in Java.

I am starting in Java and thank you for your help.

+3
source share
1 answer

If you do not know the number of lines in the file in advance, I suggest you collect the numbers in two Lists, for example 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]

If you really need numbers in two arrays int[], you can create arrays later (when the size is known).

+5
source

All Articles