Thomas V.
Thomas V.

Reputation: 71

How to parse 2 columns of ints in a txt file

I was given a set of data in a .txt document in the form of:

0   1
0   3
0   4
0   5
0   6
0   7

... and so on

My question is, how can I parse this so that I put the left column of the integers in an array, and likewise for the right column of numbers. Each pair of numbers has their own line.

In this set of data I have given, int[] leftColumn would be all zeroes and int[] rightColumn would contain 1, 3, 4, 5 ,6 ,7.

Upvotes: 2

Views: 79

Answers (3)

Ani Menon
Ani Menon

Reputation: 28209

Read the file line by line and split lines by space, then add them to the arrays.

BufferedReader br = new BufferedReader(new FileReader(<PATH/TO/FILE>));
try {
    String line = br.readLine();
    List<Integer> leftColumn = new ArrayList<>();
    List<Integer> rightColumn = new ArrayList<>();
    while (line != null) {

        String strarray[] = line.split(" ");
        for (int count = 0; count < strarray.length ; count++) {
            leftColumn.add(Integer.parseInt(strarray[count]));
            rightColumn.add(Integer.parseInt(strarray[++count]));
        }
        line = br.readLine();
    }
    System.out.println("Left Column :"+leftColumn);
    System.out.println("Right Column :"+rightColumn);
}finally {
    br.close();
}

Upvotes: 0

slartidan
slartidan

Reputation: 21576

There is a simple way of reading files, when using java8:

List<Integer> left = new ArrayList(); 
List<Integer> right = new ArrayList();

Files.lines(Paths.get("c:\\lines.txt"))
    .map(l -> l.split("\\s")) 
    .forEachOrdered(l -> {
        left.add(Integer.parseInt(l[0]));
        right.add(Integer.parseInt(l[1]));
   });

If you really need to int[]s, you can convert it later on:

int[] leftArray = left.stream().mapToInt(Integer::intValue).toArray();
int[] rightArray = right.stream().mapToInt(Integer::intValue).toArray();

Upvotes: 0

Mureinik
Mureinik

Reputation: 311393

java.util.Scanner already does most of the heavy lifting for you, it's just a matter of using it:

List<Integer> leftColumnTmp = new LinkedList<>();
List<Integer> rightColumnTmp = new LinkedList<>();
try (Scanner sc = new Scanner("myfile.txt")) {
    while (sc.hasNextLine()) {
        leftColumnTmp.add(sc.nextInt());
        rightColumnTmp.add(sc.nextInt());
    }
}

int[] leftColumn = leftColumnTmp.stream().mapToInt(Integer::intValue).toArray();
int[] rightColumn = rightColumnTmp.stream().mapToInt(Integer::intValue).toArray();

Upvotes: 2

Related Questions