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:

Writing objects to file with ObjectOutputStream




import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * Example method for using the ObjectInputStream class
     */

    public void readPersons(String filename) {
        
        ObjectInputStream inputStream = null;
        
        try {
            
            //Construct the ObjectInputStream object
            inputStream = new ObjectInputStream(new FileInputStream(filename));
            
            Object obj = null;
            
            while ((obj = inputStream.readObject()) != null) {
                
                if (obj instanceof Person) {
                
                    System.out.println(((Person)obj).toString());
                }
                
            }
            
         
        } catch (EOFException ex) { //This exception will be caught when EOF is reached
            System.out.println("End of file reached.");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the ObjectInputStream
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().readPersons("myFile.txt");
    }
}


The output from the code above looks like this:

James
Ryan
19

Obi-wan
Kenobi
30

End of file reached.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: