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 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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With