[英]read a binary file until the end
I have a series of different object serialized into a binary file.How can I read the file until the end? 我有一系列不同的对象序列化为一个二进制文件。如何读取文件直到结尾?
try {
ObjectInputStream reader = new ObjectInputStream(new FileInputStream(fname));
Object obj = reader.readObject();
if (obj instanceof Azienda) {
Azienda a = (Azienda) obj;
company.put(a.getCod(), a);
} else if (obj instanceof Privato) {
Privato p = (Privato) obj;
privato.put(p.getCod(), p);
}
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (FileNotFoundException ffe) {
System.err.println("Error: the file was not found!");
} catch (IOException ioe) {
ioe.printStackTrace();
}
in this way I read only once object per read. 这样,我每次读取仅读取一次对象。
when I read a text file I use null
当我阅读文本文件时,我使用
null
try{
while(true) {
Object obj=reader.readObject()
// do sth with object
}
}catch(EOFException e){
//we expect it so ignore
}
there is no EOF check besides the exception when you read past it for ObjectInputStream so you'll have to use the code smell called exceptions for control flow 当您阅读ObjectInputStream的异常时,除了异常之外没有EOF检查,因此您必须使用称为异常的代码气味进行控制流
ObjectInputStream reader = null;
try {
reader = new ObjectInputStream(new FileInputStream("sth"));
Object obj = null;
while ((obj = reader.readObject()) != null) {
System.out.println(obj);
}
} catch (EOFException e) {
System.out.println("finnished reading");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
System.err.println("Error: the file was not found!");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
reader.close();
}
It seems that an EOFException is thrown when there is no more object to read from the stream. 似乎没有更多对象可从流中读取时,抛出EOFException。 Unfortunately, it's not even documented.
不幸的是,它甚至没有记录。 So, I see the following solutions:
因此,我看到以下解决方案:
List<Object>
containing all the objects. List<Object>
。 This last solution, of course prevents writing the objects on the fly to the stream, and forces you to have all the objects in memory before serializing them. ObjectInputStream
does not have a concrete method for checking for end-of-file. ObjectInputStream
没有检查文件结尾的具体方法。
But every read...()
method of ObjectInputStream
throws an EOFException
when it tries to read past the end of file. 但是,当
ObjectInputStream
每个read...()
方法尝试读取文件末尾时,都会引发EOFException
。 Unfortunately this is not explicitly documented for readObject()
, but it is for all the other methods ( readInt()
etc.) 不幸的是,这并没有针对
readObject()
明确记录,而是针对所有其他方法( readInt()
等)。
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.