我基本上遇到了类似的问题:
EOFexception in Java when reading objectinputstream,但我找不到干净代码的答案.
答案指出,当读者到达文件结尾时,ObjectInputStream#readobject将抛出异常.在网上寻找解决方案之后,我还没有找到解决方案.对于这种情况,这可能是一个很好的清洁解决方案
注意:我试过这个(但它看起来很难看并且不是干净的代码).我正在寻找更好的解决方案:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); try { Object o; while ((o = ois.readobject()) != null) { if (o instanceof MyClass) { MyClass m = (MyClass)o; //use the object... } } } catch (EOFException eofex) { //do nothing } catch (IOException ioex) { throw ioex; //I have another try/catch block outside to control the life of the ObjectInputStream } //later in the code... ois.close();