(Serialization) (Java):
}
Serialization is also called as flattening, Streaming, Dehydrate (rehydrate = read), Archiving.
Serializable Interface:
By implementing this interface a class declares that is willing to be read/written by automatic serializable machinery. import java.io.*; for using serialization.
Reading:
-> System knows how to read the data from Stream and re-create object in memory
-> Downcasting is required
Code
Creating an Employee class which contains id, name , default and parameterized constructor and one method print(). To serialize an object class have to implement Serializable interface.
import java.io.*;
public class Employee implements Serializable {
private int id;
private String name;
// Default Constructor
public Employee() {
this.id = 0;
this.name = "Anonymous";
}
// Parametrized Constructor
public Employee(int i , String n) {
this.id = i;
this.name = n;
}
public void print() {
System.out.println("Id Is : " + this.id +
"\n Name Is : " + this.name );
}
}
DRIVER CLASS FOR EXECUTING PROGRAM:
public class Driver {
public static void main(String[] args) {
try {
DESERIALIZING A SINGLE OBJECT:
For reading an object from file create FileInputStream object and pass the path of file as argument:
FileInputStream fis = new FileInputStream("D:\\a.ser");
Now, create ObjectInputStream object and in its constructor pass FileInputStream object as argument:
ObjectInputStream iis = new ObjectInputStream(fis);
.readObject() is the method of ObjectInputStream class which takes zero argument and reads the serialized object from file, here that object is of Employee class and will have to cast the object to Employee class:
Employee emp = (Employee)iis.readObject();
Now, print the fields id and name on console by calling Employee .print() method:
emp.print();
} catch (Exception e) {
e.printStackTrace();
}
} }
DESERIALIZING ALL EMPLOYEE OBJECTS FROM FILE AND LOAD IN ARRAYLIST:
ArrayList<Employee> listEmployee = new ArrayList<Employee>();
import java.io.*;
import java.util.*;
public class Driver {
public static void main(String[] args) {
try {
Creating ArrayList which can hold Employee class objects:
While writing in file , in the previous example (How to write a object in file) we serialized a ArrayList object to file, So here we are deserializing the arraylist object:
FileInputStream fis = new FileInputStream("D:\\a.ser");
ObjectInputStream iis = new ObjectInputStream(fis);
Here, you can see we are casting a read object first to ArrayList:
listEmployee = (ArrayList)iis.readObject();
Now, if we want to read a object that is in its first index we do this:
Employee e = (Employee)listEmployee.get(0); // object that is at 0th index
e.print();
And reading a whole objects and display them:
for (int i = 0 ; i < listEmployee.size() ; i++) {
Employee emp2 = (Employee)listEmployee.get(i);
emp2.print();
}
0 comments:
Post a Comment