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:
- Implement Serializable interface to the class which has to be written to file
- Create a file with extension .ser. In our example it is employee.ser.
- Create ObjectOutputStream with the file created.
- Then write the object to the file
- 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(); } } }