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?
One can use the
Scannerclass and itsnextIntmethod:Output:
Basically by default, the
Scannerobject will ignore any whitespace, and will get the next token.The
Scannerclass as a constructor which takes anInputStreamas the source for the character stream, so one could use aFileInputStreamthat opens the source of the text.Replace the
Scannerinstantiation in the above example with the following: