简体   繁体   English

使用 Java 从二进制文件中读取 integer 值

[英]Reading integer values from binary file using Java

I am trying to write values greater than 256 using DataOupPutStream.write() method.我正在尝试使用DataOupPutStream.write()方法写入大于 256 的值。 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.当我尝试使用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.请参阅下面的代码片段,我想知道编译器的行为,就像它在while语句中的in.readInt()中所做的那样。

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:我运行此代码段时的 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

But when i ran in debug mode i get the following output:但是当我在调试模式下运行时,我得到以下 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)

The readInt() method is a method like any other. readInt() 方法与其他方法一样。 You are getting an EOFException because that's what the Javadoc for readInt() says will happen when you reach the end of the file.您将收到 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM