How to Write/Store an object to file in java?

Writing a Java objects to a file is called as Serialization in java. In order to do this, you have to implement the Serializable interface, and use ObjectOutputStream to write the object into a file. To do this we have created Employee class which implements java.io.Serializable.

To write an object to a stream call the writeObject() method of the ObjectOutputStream class and pass the serialized object to it.

/****************************************************************************************
 * Created on 08-2011 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java.io;

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

/**
 * Created by Vigilance India.
 * User: https://kodehelp.com
 * Date: Aug 5, 2011
 */
public class WriteObjectToFile {
    public static void main(String args[]){
        try{
            Employee employee = new Employee("0001","Robert","Newyork City","IT");

            FileOutputStream fos = new FileOutputStream("employee.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            oos.writeObject(employee);

            oos.flush();
            oos.close();
            System.out.println("Employee Object written to file employee.dat");
        }catch(IOException ex){
            ex.printStackTrace();
        }
    }

}
/****************************************************************************************
 * Created on 08-2011 Copyright(c) https://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.java.io;

import java.io.Serializable;

/**
 * Created by Vigilance India.
 * User: https://kodehelp.com
 * Date: Aug 5, 2011
 */
public class Employee implements Serializable {
    private String empId;
    private String Name;
    private String Address;
    private String Dept;

    public Employee(String empId, String name, String address, String dept) {
        this.empId = empId;
        this.Name = name;
        this.Address = address;
        this.Dept = dept;
    }

    public String toString(){
      return "[Employee: "+empId+", "+", "+Name +", "+Address+", "+Dept+"]";
    }
}

2 comments

  1. Igorstrelk says:

  2. Igorstrelk says:

Please Post Your Comments & Reviews

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.