Object serialization is a process of converting an object instance into a sequence of bytes (which may be binary).Serialized object is an object represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.After a serialized object has been written into a file, it can be read from the file and deserialized—that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.
In Java ; you can achieve Object Serialization by implement Serializable.
Here is the good convention for to make object serialization
- First implement the Serializable interface
- Your class like POJO (Plain Old Java Object)
Code Example
Employee.java
public class Employee implements Serializable {
private int empId;
private String name;
public int getEmpId() {
return empId;
}
public String getName() {
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "EMployee id : " + empId + " \nEmployee Name : " + name;
}
}
Another Main public class
pubic class Main{ public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { String filename = "data.txt"; Employee e = new Employee(); e.setEmpId(101); e.setName("Yasir Shabbir"); enter code here FileOutputStream fos = null; ObjectOutputStream out = null; fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(e); out.close(); // Now to read the object from file // save the object to file FileInputStream fis = null; ObjectInputStream in = null; fis = new FileInputStream(filename); in = new ObjectInputStream(fis); e = (Employee) in.readObject(); in.close(); System.out.println(e.toString()); } } }
No comments:
Post a Comment