Java FileInputStream ObjectInputStream到达文件EOF的结尾 [英] Java FileInputStream ObjectInputStream reaches end of file EOF

查看:310
本文介绍了Java FileInputStream ObjectInputStream到达文件EOF的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用readObject读取二进制文件中的行数,但是得到了IOException EOF。我正在做这个正确的方法吗?

pre $ FileInputStream istream = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(istream);

/ **计算物品数量** /
int line_count = 0; ((String)ois.readObject()!= null){
line_count ++;


$ / code>


解决方案

readObject()在EOF处不返回 null 。您可以捕获 EOFException 并将其解释为EOF,但是这将无法检测到与截断的文件区分正常的EOF。

更好的方法是使用一些元数据。也就是说,而不是询问 ObjectInput 流中有多少个对象,你应该把计数存储在某个地方。例如,您可以创建一个元数据类,用于记录计数和其他元数据,并将实例存储为每个文件中的第一个对象。或者您可以创建一个特殊的EOF标记类,并将实例存储为每个文件中的最后一个对象。


I am trying to read the number of line in a binary file using readObject, but I get IOException EOF. Am I doing this the right way?

    FileInputStream istream = new FileInputStream(fileName);
    ObjectInputStream ois = new ObjectInputStream(istream);

    /** calculate number of items **/
    int line_count = 0;
    while( (String)ois.readObject() != null){            
        line_count++;
    }

解决方案

readObject() doesn't return null at EOF. You could catch the EOFException and interpret it as EOF, but this would fail to detect distinguish a normal EOF from a file that has been truncated.

A better approach would be to use some meta-data. That is, rather than asking the ObjectInput how many objects are in the stream, you should store the count somewhere. For example, you could create a meta-data class that records the count and other meta-data and store an instance as the first object in each file. Or you could create a special EOF marker class and store an instance as the last object in each file.

这篇关于Java FileInputStream ObjectInputStream到达文件EOF的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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