Serialization in java is a mechanism of writing the state of an object into a byte stream.
Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability.
It must be implemented by the class whose object you want to persist.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
Let's see the example given below :-
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Employee implements Serializable{
private static final long serialVersionUID = -7343212483392987741L;
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class SerialiazableExample {
static void storeObject(Employee emp,String filePath) throws IOException { //Java Serialization Method
FileOutputStream os = new FileOutputStream(filePath);
ObjectOutputStream ob = new ObjectOutputStream(os);
ob.writeObject(emp);
ob.flush();
ob.close();
System.out.println("Object Written In File Successfully.."+filePath);
}
static void displayObject(String filePath) throws IOException, ClassNotFoundException{ // Java Deserialization Method
System.out.println("READING DATA FROM FILE:::");
FileInputStream is = new FileInputStream(filePath);
ObjectInputStream ob = new ObjectInputStream(is);
Employee emp = (Employee)ob.readObject();
System.out.println("NAME\tID");
System.out.println("----\t--");
System.out.println(emp.getId()+"\t"+emp.getName());
ob.close();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
String filePath = "D:/serializable_file.txt";
Employee e = new Employee();
e.setName("Pushkar Khosla");
e.setId(101);
storeObject(e,filePath);
displayObject(filePath);
}
}
Programs Output:-


