我试图使用readObject读取二进制文件中的行数,但我得到了IOException EOF。我这样做是对的吗?
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++;
}
发布于 2010-04-13 07:59:14
readObject()
在EOF中不返回null
。您可以捕获EOFException
并将其解释为EOF,但这将无法检测到区分正常的EOF和已被截断的文件。
更好的方法是使用一些元数据。也就是说,您应该将计数存储在某个地方,而不是询问ObjectInput
流中有多少个对象。例如,您可以创建一个元数据类来记录计数和其他元数据,并将一个实例存储为每个文件中的第一个对象。或者,您可以创建一个特殊的EOF标记类,并将一个实例存储为每个文件中的最后一个对象。
发布于 2012-11-13 22:29:12
今天我也遇到了同样的问题。尽管这个问题很古老,但问题仍然存在,并且没有提供干净的解决方案。应避免忽略EOFException
,因为当某个对象未正确保存时,可能会抛出此错误。写入null显然会阻止您将NULL值用于任何其他目的。最后,在对象流上使用available()
总是返回零,因为对象的数量是未知的。
我的解决方案很简单。ObjectInputStream
只是其他流的包装器,比如FileInputStream。尽管ObjectInputStream.available ()
返回零,但FileInputStream.available将返回一些值。
FileInputStream istream = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(istream);
/** calculate number of items **/
int line_count = 0;
while( istream.available() > 0) // check if the file stream is at the end
{
(String)ois.readObject(); // read from the object stream,
// which wraps the file stream
line_count++;
}
发布于 2010-04-13 15:37:12
不是的。捕获EOFException
并使用它来终止循环。
https://stackoverflow.com/questions/2626163
复制相似问题