In this quick article, you'll learn how to write a Java Object to a file in the local file system. To do this serialization, the class of the object must implement the Serializable interface. This will enable us to perform basic I/O operations on the class in Java.

To write an object to a file, all you need to do is the following:

  • Create a Java class that implements the Serializable interface.
  • Open a new or an existing file using FileOutputStream.
  • Create an instance of ObjectOutputStream and pass FileOutputStream as an argument to its constructor.
  • Use ObjectOutputStream.writeObject() method to write the object to the file.

Create Java Class

Let us first create a simple Java class named User.java and implement the Serializable interface:

public class User implements Serializable {

    public String name;
    public String email;
    private String[] roles;
    private boolean admin;

    public User() {
    }

    public User(String name, String email, String[] roles, boolean admin) {
        this.name = name;
        this.email = email;
        this.roles = roles;
        this.admin = admin;
    }

    // getters and setters, toString() .... (omitted for brevity)
}

Write Object to File

The following example demonstrates how you can create a User object and write it to a file in Java 7 or higher:

try (FileOutputStream fos = new FileOutputStream("object.dat");
     ObjectOutputStream oos = new ObjectOutputStream(fos)) {

    // create a new user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // write object to file
    oos.writeObject(user);

} catch (IOException ex) {
    ex.printStackTrace();
}

In older Java versions (Java 6 or below), you have to manually close ObjectOutputStream as shown below:

try {
    FileOutputStream fos = new FileOutputStream("object.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    // create a new user object
    User user = new User("John Doe", "john.doe@example.com",
            new String[]{"Member", "Admin"}, true);

    // write object to file
    oos.writeObject(user);

    // close writer
    oos.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.