How do I write an object to a file and read it back?
Author: Deron Eriksson
Description: This Java tutorial describes how to write an object to a file and read it back.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


A JavaSW class needs to implement the Serializable interface if we'd like to be able to save the state of an object of that class. SerializationW allows us to do things like save an object's state to a file in the file system or transfer the object across a network. As an example, the MyBean class implements the Serializable interface.

MyBean.java

package test;

import java.io.Serializable;

public class MyBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private String one;
	private String two;

	public MyBean() {
	}

	public MyBean(String one, String two) {
		this.one = one;
		this.two = two;
	}

	public String getOne() {
		return one;
	}

	public void setOne(String one) {
		this.one = one;
	}

	public String getTwo() {
		return two;
	}

	public void setTwo(String two) {
		this.two = two;
	}

}

The FileSerialization class creates a MyBean object via its two-argument constructor. It writes the object to a file called "mybean.ser" via an ObjectOutputStream. After that, it reads the "mybean.ser" file via an ObjectInputStream, loading the object state into a MyBean object. It then displays the values stored in the object.

FileSerialization.java

package test;

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

public class FileSerialization {

	public static void main(String[] args) {

		try {
			MyBean mb = new MyBean("first value", "second value");

			// write object to file
			FileOutputStream fos = new FileOutputStream("mybean.ser");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(mb);
			oos.close();

			// read object from file
			FileInputStream fis = new FileInputStream("mybean.ser");
			ObjectInputStream ois = new ObjectInputStream(fis);
			MyBean result = (MyBean) ois.readObject();
			ois.close();

			System.out.println("One:" + result.getOne() + ", Two:" + result.getTwo());

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

Executing the FileSerialization class generates the following expected output to the console:

One:first value, Two:second value