I found this page that suggests looping until exceptions is thrown and then handle that exception.
Basically what it suggests is:
[...]
try {
while (true) {
objectInputStream.readObject();
}
}
catch ( EOFException e ) {
\\ This ALWAYS happens
}
[...]
However as Bloch put it in Effective Java, one should only "Use exceptions for exceptional conditions" and there isn't really anything exceptional about the inputstream not containing an infinite number of objects now is there? It is going to happen every single time!
Since there is no hasNext method on the ObjectInputStream, what can I do? Am I really stuck with using an Exception for knowing when there are no more Objects available to read?
A number of ways to do this, all of them fine, in my opinion:
use the exception. The API designers didn't include a method, as you said, to check whether there is more, so it's partly their fault
use a marker object when writing to the stream. For example Integer.MAX_VALUE or a custom EOFMarker object. If it is found, stop.
Don't write the objects themselves, but write a List instead. Then read the list
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