Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read formatted input in Java?

Tags:

java

io

input

Suppose my input file contains:

3 4 5 6    7        8
9


10

I want to run a while loop and read integers, so that I will get 3,4,5,6,7,8 and 10 respectively after each iteration of the loop.

This is really simple to do in C/C++ but not in Java...

I tried this code:

try {
            DataInputStream out2 = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));

            int i=out2.read();
            while(i!=-1){
                System.out.println(i);
                i=out2.readInt();
            }

    } catch (IOException ex) {

    }

and what I get is:

51
540287029
540418080
538982176
151599117
171511050
218762506
825232650

How do I read the integers from this file in Java?

like image 515
Lazer Avatar asked Sep 12 '09 06:09

Lazer


1 Answers

One can use the Scanner class and its nextInt method:

Scanner s = new Scanner("3  4        5   6");

while (s.hasNext()) {
  System.out.println(s.nextInt());
}

Output:

3
4
5
6

Basically by default, the Scanner object will ignore any whitespace, and will get the next token.

The Scanner class as a constructor which takes an InputStream as the source for the character stream, so one could use a FileInputStream that opens the source of the text.

Replace the Scanner instantiation in the above example with the following:

Scanner s = new Scanner(new FileInputStream(new File(filePath)));
like image 167
coobird Avatar answered Sep 29 '22 09:09

coobird