使用Java从二进制文件读取整数值

时间:2011-05-26 08:26:26

标签: java file-io binaryfiles java-io

我正在尝试使用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)

1 个答案:

答案 0 :(得分:7)

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]