读取文件时出现 EOFException

EOFException from reading a file

输出是正确的,但后面跟着一个 EOFException。我阅读了文档,但我仍然不知道如何解决这个问题

try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.bin"))){
    for(Ser s = (Ser)ois.readObject(); s!=null; s=(Ser)ois.readObject() )
        System.out.println(s);
}catch (IOException | ClassNotFoundException e){
    e.printStackTrace();
}

如果没有数据,您假设 readObject returns 为 null,但实际上它会抛出 EOFException。最简单的修复就是捕获异常:

try(...) {
    for(;;) {
        Ser s = (Ser)ois.readObject();
        System.out.println(s);
    }
} catch(EOFException e) {
    // normal loop termination
} catch(IOException | ClassNotFoundException e){
    // error
}

请注意,有些人和编码标准认为在非错误条件下抛出异常是不好的做法,例如在这种情况下到达输入末尾。