使用Java从二进制文件读取整数值 [英] Reading integer values from binary file using Java

查看:289
本文介绍了使用Java从二进制文件读取整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

请参考下面的代码片段,我想了解编译器的行为,就像它在while语句内的in.readInt()中所做的一样.

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.

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)

推荐答案

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

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.

我跑步时

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]

这篇关于使用Java从二进制文件读取整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆