Java – eofexception when reading files using objectinputstream
I have basically encountered a similar problem: eofexception in Java when reading objectinputstream, but I can't find the answer of clean code
The answer indicates that objectinputstream#readobject will throw an exception when the reader reaches the end of the file After looking for a solution online, I haven't found a solution yet In this case, this may be a good cleaning solution
Note: I've tried this (but it looks ugly and isn't clean code) I am looking for a better solution:
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();
Solution
This is what should happen Your code is wrong Check Javadoc If NULL is written, readobject() returns only null It doesn't say anything about returning null in EOF The loop until readObject () returns null will only stop when you write null through writeobject (). If not, you will get an eofexception