使用ObjectInputStream在java中反序列化时如何检查EOF

使用ObjectInputStream在java中反序列化时如何检查EOF,java,deserialization,fileinputstream,objectinputstream,Java,Deserialization,Fileinputstream,Objectinputstream,我正在尝试使用ObjectInputStream对java中的某些文件进行反序列化。我能够成功读取所有对象,但得到EOFEException。无法找到检查EOFEException的方法。 尝试下面的代码。 如有任何建议,我们将不胜感激 谢谢你的帮助 List destinationList=new ArrayList(); try(ObjectInputStream in=newobjectinputstream(newfileinputstream(fileName))){ 目的地=空; w

我正在尝试使用ObjectInputStream对java中的某些文件进行反序列化。我能够成功读取所有对象,但得到EOFEException。无法找到检查EOFEException的方法。 尝试下面的代码。 如有任何建议,我们将不胜感激

谢谢你的帮助

List destinationList=new ArrayList();
try(ObjectInputStream in=newobjectinputstream(newfileinputstream(fileName))){
目的地=空;
while(true){
destination=.readObject()中的(destination);
如果(目标==null)
打破
destinationList.add(目的地);
}
//这里有一些代码
}捕获(例外e){
e、 printStackTrace();
}

**注意:-**我只有序列化文件。

EOFEException表示您的
ObjectInputStream
在读取序列化对象时已到达文件结尾,这意味着在大多数情况下文件已损坏,或者您在
ObjectInputStream
达到
eof
后仍在读取,考虑到您编写代码的方式,您可以通过在
catch
子句中声明来检查代码:

List destinationList=new ArrayList();
try(ObjectInputStream in=newobjectinputstream(newfileinputstream(fileName))){
目的地=空;
while(true){
destination=.readObject()中的(destination);
如果(目标==null)
打破
destinationList.add(目的地);
}
//这里有一些代码
}捕获(EOFEception eofEx){
eofEx.printStackTrace();
}捕获(例外e){
e、 printStackTrace();
}
但我不认为这是你想要的,你需要的是一种没有这个问题的读取对象的方法,你可以这样做:

List destinationList=new ArrayList();
try(ObjectInputStream in=newobjectinputstream(newfileinputstream(fileName))){
目的地=空;
while(true){
试一试{
destination=.readObject()中的(destination);
destinationList.add(目的地);
}捕获(EOFEception eofEx){
打破
}
}
//这里有一些代码
}捕获(例外e){
e、 printStackTrace();
}

无论如何,结果都是一样的。

ObjectInputStream.readObject
不会为输入结束返回
null


对于
null
终止的对象列表,您可以使用
ObjectOutputStream在文件末尾写入
null
。writeObject

请提供堆栈跟踪并提供用于序列化的代码以及用于响应的堆栈。但我不是创建这个系列化文件的人。尽管我会在创建任何其他序列化文件时尝试您的解决方案。
    List<Destination> destinationList = new ArrayList<Destionation>();
    try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName))) {
      Destination destination = null;
            while(true) {
                destination = (Destination) in.readObject();
                if(destination == null)
                    break;

                destinationList.add(destination);
            }

            // Some code here

    } catch (Exception e) {
        e.printStackTrace();
    }