Reading integer values ​​from binary using Java

I am trying to write values ​​greater than 256 using a method DataOupPutStream.write(). When I try to read the same value with DataInputStream.read(), it will return 0. So, I used methods DataOutputStream.writeInt()and DataInputStream.readInt()for recording and producing values greater than 256, and it works fine.

See the code snippet below. I would like to know the behavior of the compiler as what it does in the in.readInt()statement inside while.

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);
}

Result when I ran this snippet:

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 was working 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)
+3
source share
1 answer

readInt() - , . EOFException, , Javadoc readInt(), , .


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();

.

257
2
2123
223
2132
[EOF]
+7

All Articles