Writing objects to file with ObjectOutputStream


You can use the ObjectOutputStream class to write objects to an underlying stream.
In this code example we use it to write objects to a file using the FileOutputStream class as argument to the ObjectOutputStream constructor.
The class from which we create objects to write is a simple java class with three attributes, first name, last name and age. The important thing here is that it implements the Serializable interface.
Any object that is written on an ObjectOutputStream is serialized and therefore has to implement either the java.io.Serializable interface or the java.io.Externalizable interface.

This is what the Person class looks like:


import java.io.Serializable;

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

public class Person implements Serializable {
    
    private String firstName;
    private String lastName;
    private int age;
    
    /**
     * Creates a new instance of Person
     */

    public Person() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    //Overriding toString to be able to print out the object in a readable way
    //when it is later read from the file.
    public String toString() {
        
        StringBuffer buffer = new StringBuffer();
        buffer.append(firstName);
        buffer.append("\n");
        buffer.append(lastName);
        buffer.append("\n");
        buffer.append(age);
        buffer.append("\n");
        
        return buffer.toString();
    }
    
    
}


This is the code for creating instances of the Person class and writing them to an ObjectOuputStream:


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

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

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

    public void writePersons(String filename) {
        
        ObjectOutputStream outputStream = null;
        
        try {
            
            //Construct the LineNumberReader object
            outputStream = new ObjectOutputStream(new FileOutputStream(filename));
            
            Person person = new Person();
            person.setFirstName("James");
            person.setLastName("Ryan");
            person.setAge(19);
            
            outputStream.writeObject(person);
            
            person = new Person();
            
            person.setFirstName("Obi-wan");
            person.setLastName("Kenobi");
            person.setAge(30);
            
            outputStream.writeObject(person);
            
            
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the ObjectOutputStream
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */

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

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: