How to read binary file until the end-of-file?
I need to read binary file including the eof
.
I read file using DataInputStream
DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream( fileName ) ) );
And I used readInt();
to read binary file as an integer.
try {
while ( true){
System.out.println(instr.readInt());
sum += instr.readInt(); //sum is integer
}
} catch ( EOFException eof ) {
System.out.println( "The sum is: " + sum );
instr.close();
}
But this program doesn't read the End-of-file or last line of text(if it's text file). So if the text file开发者_JAVA百科 is only contained only one line of text, the sum is 0. Please help me with this.
Example: if .txt
file containing the text.
a
b
c
readInt();
just only reads a
and b
.
That's indeed normal. You are trying to read the bytes, and not ints. The readInt()
method melts four bytes together to an int.
Let's analyse your example file:
a
b
c
This is totally 5 bytes: a
, \n
, b
, \n
, c
.
\n
are newlines.
The readInt()
method takes the four first bytes and makes an int of it. This means when you try to make a second call to it, there is only one byte left, which is not enough.
Try to use readByte()
instead, which will return all the bytes, one by one.
To demonstrate, this is the body of the readInt()
method, it calles 4 times read()
:
public final int readInt() throws IOException {
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
When the end of a file is reached, -1
is returned from the read()
method. That is how EOFExceptions are detected.
In your case it might be better to use a Reader and use .next() and .nextLine()
FileReader reader = new FileReader(fileName);
Scanner scanner = new Scanner(reader );
String sum;
while (scanner.hasNext()) {
sum += scanner.next()) {
}
reader.close();
System.out.println( "The sum is: " + sum );
精彩评论