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

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.

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)

解决方案

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.

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值