Write An Object To File In Java (Serialization)

Java objects can be written to a file. If you implement Serializable interface to a class, implicitly that class is eligible for the serialization. Serializable is a marker interface which doesn’t have any methods defined. Serialization is the concept where an object can be converted to byte streams and transferred to the network. It is very much useful in the net work programming. (Also Read : What is transient variable?). In the below example, I have written a simple example to convert Employee object to an object using the ObjectOutputStream.

Summary of the steps for below program:

  1. Implement Serializable interface to the class which has to be written to file
  2. Create a file with extension .ser. In our example it is employee.ser.
  3. Create ObjectOutputStream with the file created.
  4. Then write the object to the file
  5. A file (employee.ser) will be created in the path you have specified

Employee.java

package javabeat.net.core;

import java.io.Serializable;

public class Employee implements Serializable{
	private String name;
	private String empId;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmpId() {
		return empId;
	}
	public void setEmpId(String empId) {
		this.empId = empId;
	}
	public String toString(){
		String str = "Name : " + this.name+", ID : " + this.empId;
		return str;
	}
}

SerializationExample.java

package javabeat.net.core;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializationExample {
	public static void main(String args[]) {

		SerializationExample serializationVar = new SerializationExample();
		serializationVar.serializeEmployee("Krishna", "India");
	}

	public void serializeEmployee(String name, String id) {

		Employee address = new Employee();
		address.setName(name);
		address.setEmpId(id);

		try {

			FileOutputStream fileout = new FileOutputStream("employee.ser");
			ObjectOutputStream objout = new ObjectOutputStream(fileout);
			objout.writeObject(address);
			objout.close();
			System.out.println("Serialization To Object Is Completed!!");

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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better