使用 Java 从二进制文件中读取整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6135668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading integer values from binary file using Java
提问by rozar
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.
我正在尝试使用DataOupPutStream.write()
方法写入大于 256 的值。当我尝试使用DataInputStream.read()
它读取相同的值时,它将返回 0。因此,我使用DataOutputStream.writeInt()
和DataInputStream.readInt()
方法来写入和检索大于 256 的值并且它工作正常。
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.
请参阅下面的代码片段,我想知道编译器的行为以及它在语句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);
}
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)
回答by Peter Lawrey
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.
readInt() 方法与其他方法一样。您收到 EOFException ,因为这是 readInt() 的 Javadoc 所说的,当您到达文件末尾时会发生这种情况。
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]