How to read and write Java object to a file

Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization.

A Java object is serializable if its class or any of its superclasses implement either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

1. Java Object

Person.java

package com.mkyong;

import java.io.Serializable;

public class Person implements Serializable {

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

	Person() {
	};

	Person(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
	}
}

2. Writing and Reading objects in Java

The objects can be converted into byte-stream using java.io.ObjectOutputStream. In order to enable writing of objects into a file using ObjectOutputStream, it is mandatory that the concerned class implements Serializable interface as shown in the class definition below.

Reading objects in Java are similar to writing object using ObjectOutputStreamObjectInputStream. Below example shows the complete cycle of writing objects and reading objects in Java.

On reading objects, the ObjectInputStream directly tries to map all the attributes into the class into which we try to cast the read object. If it is unable to map the respective object exactly then it throws a ClassNotFound exception.

Let us now understand the writing and reading process using an example. We are using the Person class shown above as an object.

WriterReader.java

package com.mkyong;

package com.mkyong;

import java.io.File;
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 WriterReader {

	public static void main(String[] args) {

		Person p1 = new Person("John", 30, "Male");
		Person p2 = new Person("Rachel", 25, "Female");

		try {
			FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
			ObjectOutputStream o = new ObjectOutputStream(f);

			// Write objects to file
			o.writeObject(p1);
			o.writeObject(p2);

			o.close();
			f.close();

			FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
			ObjectInputStream oi = new ObjectInputStream(fi);

			// Read objects
			Person pr1 = (Person) oi.readObject();
			Person pr2 = (Person) oi.readObject();

			System.out.println(pr1.toString());
			System.out.println(pr2.toString());

			oi.close();
			fi.close();

		} catch (FileNotFoundException e) {
			System.out.println("File not found");
		} catch (IOException e) {
			System.out.println("Error initializing stream");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

On executing the above code, we get below output:


Name:John
Age: 30
Gender: Male
Name:Rachel
Age: 25
Gender: Female

References

  1. Serialization Java Docs
  2. ObjectInputStream Java Docs
  3. ObjectOutputStream Java Docs

About the Author

author image
Datsabk
A technically sound person, oriented towards learning things logically rather than technically. It is my logical approach that has helped me learn and take up any programming language and start with coding. With a responsibility of Java based Web development professionally, I highly believe in imparting knowledge online for any technical subject that I can handle.

Comments

Leave a Reply

avatar
newest oldest most voted
Reeshabh Ranjan
Guest
Reeshabh Ranjan

Oh my God, you have the best tutorials out of everyone on the first search result page of Google. Awesome!