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


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;


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();

		try {

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

		} catch (Exception ex) {

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>