How to write object to a file in java

If you want to send object over network, then you need to  write object to a file and convert it to the stream. This process can be referred as serialization.

Object needs to implement Serializable interface which is marker interface  interface and we will use to write object to a file.

Java Serialization Tutorial:

    Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java
Lets go through steps for writing object to a file.

Lets take an example:
Create in src->org.arpit.java2blog
package org.arpit.java2blog;
public class Employee implements Serializable{ 
   private static final long serialVersionUID = 1L;    
  int employeeId;
    String employeeName;
    String department;
    public int getEmployeeId() {
        return employeeId;
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    public String getEmployeeName() {
        return employeeName;
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    public String getDepartment() {
        return department;
    public void setDepartment(String department) {
        this.department = department;
As you can see above,if you want to serialize any class then it must implement Serializable interface which is marker interface.
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface
Create in src->org.arpit.java2blog
package org.arpit.java2blog;
 public class SerializeMain {

  * @author Arpit Mandliya
 public static void main(String[] args) {

  Employee emp = new Employee();
   FileOutputStream fileOut = new FileOutputStream("employee.ser");
   ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
  }catch(IOException i)
When you run above program,employee.ser will get created. Its content won't be in human readable format but it will have object stored on file . You can use ObjectInputStream to read same object from file.

These are some simple steps to write object to a file. If you want to go through some complex scenario you can go through Serialization in java

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012