加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 08:40:44 所属栏目:Java 来源:网络整理
导读:我试图使用DataOupPutStream.write()方法写入大于256的值.当我尝试使用DataInputStream.read()读取相同的值时,它将返回0.因此,我使用DataOutputStream.writeInt()和DataInputStream.readInt()方法来编写和检索大于256的值,并且它工作正常. 请参阅下面的代码
我试图使用DataOupPutStream.write()方法写入大于256的值.当我尝试使用DataInputStream.read()读取相同的值时,它将返回0.因此,我使用DataOutputStream.writeInt()和DataInputStream.readInt()方法来编写和检索大于256的值,并且它工作正常.

请参阅下面的代码片段我想知道编译器的行为,就像它在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);
}

运行此代码段时的输出是:

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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读