Reading objects from file using ObjectInputStream



This example shows how to read objects that has been serialized to a file with an ObjectOutputStream.
We simply create an instance of ObjectOuputStream and loop for as long as there are objects in the file.

The while condition could be argued since the readObject method will never return null, instead it will throw an EOFException when the end of the file is reached.
One could as well write ‘while (true)’ but as that is not good practice we won’t do it here either. This example presumes that the number of objects in the file is unknown and therefore we cannot use a fixed number of iterations in the loop.

What this code example does instead is to catch the EOFException and just print out that the end of file is reached.
The file contains instances of the class Person and it was used in the corresponding example when an ObjectOutputStream was used to write objects to a file.

See this link for further information about the Person class.

The output from the code above looks like this:







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">