forked from hotwax/training-assignment
-
Notifications
You must be signed in to change notification settings - Fork 0
Module 2: Serialization
Rishabh Malviya edited this page Feb 7, 2023
·
1 revision
The ObjectOuputStream class of java.io package can be used to write objects that can be read by ObjectInputStream.
They are used to serialize objects. Serialization is the process of converting an object into a stream of bytes. The stream of bytes can be saved to a file or sent over a network. The stream of bytes can be converted back into an object. This process is called deserialization.
import java.io.*;
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new Integer(42));
oos.close();import java.io.*;
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream ois = new ObjectInputStream(fis);
Integer i = (Integer) ois.readObject();
ois.close();An object graph contains a set of objects that are automatically serialized given that the object that contains the reference is serialized too. Any object that is serialized and contains an object reference, the object reference will be serialized by the JVM.
import java.io.*;
class A implements Serializable {
B b;
}
class B implements Serializable {
C a;
}
class C implements Serializable {
int i = 10;
}
public class Main {
public static void main(String[] args) throws Exception {
A a = new A();
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream ois = new ObjectInputStream(fis);
A a2 = (A) ois.readObject();
ois.close();
// Output : a2.b.a.i = 10
}
}- Java classes which require user defined handling of serialization and deserialization, they need to use
readObjectandwriteObjectmethods. - The writeObject method writes the byte stream in physical location.
- The readObject method is used to read byte stream from physical location and type cast to required class.
import java.io.*;
class A implements Serializable {
B b;
private void writeObject(ObjectOutputStream oos) throws Exception {
oos.defaultWriteObject();
oos.writeInt(b.i);
}
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
b = new B(ois.readInt());
}
}
class B implements Serializable {
int i;
B(int i) {
this.i = i;
}
}
public class Main {
public static void main(String[] args) throws Exception {
A a = new A();
a.b = new B(10);
FileOutputStream fos = new FileOutputStream("temp.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();
FileInputStream fis = new FileInputStream("temp.out");
ObjectInputStream ois = new ObjectInputStream(fis);
A a2 = (A) ois.readObject();
ois.close();
// Output : a2.b.i = 10
}
}