DataInputStream
readInt()
Here is a program that reads four integers, adds them up, and writes the sum (as characters) to the monitor. It expects a data file "intData.dat".
import java.io.*; class ReadInts { public static void main ( String[] args ) { String fileName = "intData.dat" ; long sum = 0; try { DataInputStream instr = new DataInputStream( new BufferedInputStream( new FileInputStream( fileName ) ) ); sum += instr.readInt(); sum += instr.readInt(); sum += instr.readInt(); sum += instr.readInt(); System.out.println( "The sum is: " + sum ); instr.close(); } catch ( IOException iox ) { System.out.println("Problem reading " + fileName ); } } }
The method readInt()
grabs
four bytes from the input stream and returns them as an
int
.
That value can be used in arithmetic without conversion.
(No parseInt()'s
in this program).