I basically have a similar problem as stated here: EOFexception in Java when reading objectinputstream, but I don't find an answer with clean code.
The answer states that the ObjectInputStream#readObject
will throw the exception when the reader reachs the End Of File. After looking in the web for a solution, I haven't found a solution. Could be a good and clean solution for this case?
Note: I have tried this (but it looks ugly and is not clean code). I'm 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();
That's what's supposed to happen. Your code is wrong. Check the Javadoc. readObject()
only returns null
if you wrote a null
. It doesn't say anything about returning a null at EOF. Looping until readObject()
returns null
will only stop if you ever wrote a null
via writeObject()
, and if you didn't you will get an EOFException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With