Java IO Tutorial

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jeff
8 years ago

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.

Shane
10 years ago

@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!

Manjeet
11 years ago

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

M Chandry
2 years ago

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

Sid
4 years ago

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

Alexander_Ochs
8 years ago

Thank you =)

Mitrajit Samanta
11 years ago

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.

Amy Xiao
11 years ago

Good tutorial~~
But the file is garbled, how to fix this?