The sum is: 255
import java.io.*; class ReadLongs { 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.readLong(); sum += instr.readLong(); System.out.println( "The sum is: " + sum ); instr.close(); } catch ( IOException iox ) { System.out.println("Problem reading " + fileName ); } } }
The new program reads two 8-byte long
s.
(The previous program read four 4-byte int
s.)
Each program reads in a total of 16 bytes, but the bytes are used
in different ways.
This new program uses the same data file (and the same bytes) as the previous program.
Here is a sample run:
C:\Programs>java ReadLongs The sum is: 1099511627776 C:\Programs>
The program used the same input file and read in the same bytes as the previous program, but computed a different answer. What happened?
Well, this program read the first 8 bytes of the file
as a long
value.
But when those 8 bytes were written, they were intended to be two 4-byte int
s.
Then the second 8 bytes were read as another long
value.
But they, also, were intended to be two int
s.
In other words, the new program interpreted the bytes of the file incorrectly.
No wonder it computed a strange answer!
Could the program be written so that it checks for valid input?