How to write an object to file in Java (ObjectOutputStream)

This example shows how to use ObjectOutputStream to write objects to a file in Java, aka Serialization.


  public static void writeObjectToFile(Person obj, File file) throws IOException {
      try (FileOutputStream fos = new FileOutputStream(file);
           ObjectOutputStream oos = new ObjectOutputStream(fos)) {
          oos.writeObject(obj);
          oos.flush();
      }
  }

1. Java object

We can serialize or marshal an object which implements a Serializable interface.

Person.java

package com.mkyong.io.object;

import java.io.Serializable;
import java.math.BigDecimal;

public class Person implements Serializable {

    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    // if transient, JVM ignore this field for serialization
    private transient BigDecimal salary;

    public Person(String name, int age, BigDecimal salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

2. Write Object to File

The below example will write the Person object into a file named person.bin.

HelloSerializationFile.java

package com.mkyong.io.object;

import java.io.*;
import java.math.BigDecimal;

public class HelloSerializationFile {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Person person = new Person("mkyong", 50, new BigDecimal(1000));

        File file = new File("person.bin");

        writeObjectToFile(person, file);

        Person p = readObjectFromFile(file);

        System.out.println(p);

    }

    // Serialization
    // Save object into a file.
    public static void writeObjectToFile(Person obj, File file) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(obj);
            oos.flush();
        }
    }

    // Deserialization
    // Get object from a file.
    public static Person readObjectFromFile(File file) throws IOException, ClassNotFoundException {
        Person result = null;
        try (FileInputStream fis = new FileInputStream(file);
             ObjectInputStream ois = new ObjectInputStream(fis)) {
            result = (Person) ois.readObject();
        }
        return result;
    }

}

Output

Terminal

  Person{name='mkyong', age=50, salary=null}

3. More Serialization examples


  // Serialization
  // Save object into a file.
  public static void writeObjectToFile(Person obj, File file) throws IOException {
      try (FileOutputStream fos = new FileOutputStream(file);
           ObjectOutputStream oos = new ObjectOutputStream(fos)) {
          oos.writeObject(obj);
          oos.flush();
      }
  }

  // Serialization
  // Convert object to OutputStream
  public static void writeObjectToStream(Object obj, OutputStream output) throws IOException {
      try (ObjectOutputStream oos = new ObjectOutputStream(output)) {
          oos.writeObject(obj);
          oos.flush();
      }
  }

  // Serialization
  // Convert object to byte[]
  public static byte[] writeObjectToStream(Object obj) {
      ByteArrayOutputStream boas = new ByteArrayOutputStream();
      try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
          ois.writeObject(obj);
          return boas.toByteArray();
      } catch (IOException ioe) {
          ioe.printStackTrace();
      }
      throw new RuntimeException();
  }

Download Source Code

$ git clone https://github.com/mkyong/core-java.git

$ cd java-io/com/mkyong/io/object

References

13 comments on “How to write an object to file in Java (ObjectOutputStream)

  1. Thanks for your site. I like the down to earth code examples!

    Can you please explain about using toString() for printing Objects to the file in the same “style”/”Format”?

    Regards

    Reply
  2. Hi I have been getting the error ‘java.io.NotSerializableException’ on line ‘oos = new ObjectOutputStream(fout);’
    Do you have a work around for this?

    Reply
    1. For serialization, the object must implement the Serializable interface.

      Reply
  3. Mkyong always bringing up the real world examples and a solution for it.
    You help me a lot with your posts.
    Thank you very much.
    keep up with your work.

    Reply
  4. @Amy, @ Manjeet: The file will be garbled as it wont save it directly in ASCII readable characters. It will convert it to a serialized binary stream, when you view that stream in the file it won’t be readable (but thats normal). If you read the file back into an object the data will be the same.

    @Mitrajit: You best off creating an object for yor 3D data that will store your geometry such as X, Y, Z, type of object, size or object, etc and then saving that object to file rather than saving the physical entity.

    @mkyong: Thanks for the insight, I was looking for something a little more robust than this, but this a step in the right direction. Thanks!

    Reply
  5. my file is having junk character after file writing is done 🙁
    how to fix it ??

    Reply
  6. Thanks for your tutorial, its really helpful.

    your program runs perfectly with string data, but what if we use java3d object such as ColorCube, Sphere….?
    I have a java3d program that needs to be write various java3d objects in a object file for later use. But I can’t do it. Please help me.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *