我正在尝试使用DataOupPutStream.write()方法编写大于256的值。当我尝试使用DataInputStream.read()读取相同的值时,它将返回0。因此,我使用DataOutputStream.writeInt()DataInputStream.readInt()方法编写和检索大于256的值,并且工作正常。

请参考下面的代码片段,我想知道编译器的行为,就像它在in.readInt()语句内的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);
}

当我运行此代码段时,输出为:
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

但是当我以调试模式运行时,我得到以下输出:
2123
223
2132
Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(Unknown Source)
    at compress.DataIOStream.main(DataIOStream.java:34)

最佳答案

readInt()方法与其他方法一样。之所以收到EOFException,是因为当您到达文件末尾时,readInt()的Javadoc就会发生这种情况。

当我跑步

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]

10-04 18:29