Reading integer values from binary file using Java

2020-07-20 05:10发布

问题:

I am trying to write values greater than 256 using DataOupPutStream.write() method. When i try reading the same value using DataInputStream.read() it will return 0. So, i used DataOutputStream.writeInt() and DataInputStream.readInt() methods to write and retrieve values greater than 256 and it is working fine.

Refer the below code snippet i would like to know the behaviour of the compiler as what it does in the in.readInt() inside the while statement.

FileOutputStream fout = new FileOutputStream("T.txt");
BufferedOutputStream buffOut = new BufferedOutputStream(fout);
DataOutputStream out = new DataOutputStream(fout);

Integer output = 0;
out.writeInt(257);
out.writeInt(2);
out.writeInt(2123);
out.writeInt(223);
out.writeInt(2132);
out.close();

FileInputStream fin = new FileInputStream("T.txt");
DataInputStream in = new DataInputStream(fin);

while ((output = in.readInt()) > 0) {
    System.out.println(output);
}

The Output when i ran this snippet is :

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at compress.DataIOStream.main(DataIOStream.java:34)
257
2
2123
223
2132

But when i ran in debug mode i get the following output :

2123
223
2132
Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at compress.DataIOStream.main(DataIOStream.java:34)

回答1:

The readInt() method is a method like any other. You are getting an EOFException because that's what the Javadoc for readInt() says will happen when you reach the end of the file.


When I run

DataOutputStream out = new DataOutputStream(new FileOutputStream("T.txt"));
out.writeInt(257);
out.writeInt(2);
out.writeInt(2123);
out.writeInt(223);
out.writeInt(2132);
out.close();

DataInputStream in = new DataInputStream(new FileInputStream("T.txt"));
try {
    while (true) 
        System.out.println(in.readInt());
} catch (EOFException ignored) {
    System.out.println("[EOF]");
}
in.close();

I get this in normal and debug mode.

257
2
2123
223
2132
[EOF]