Advantage:
It is mainly used to travel object's state on the network.
ObjectOutputStream Class:
An ObjectOutputStream is used to write primitive data type and java objects to an OutputStram. Only objects that support the java.io.Serializable interface can be written to streams.(Byte From)
Deserialization is the process of reconstructing the object from the serialized state. it is the reverse operation of serialization.
ObjectInputStream class:
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.
Serialization Java code..
package com.najathi.www;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Ser implements Serializable {
int id;
String name;
public Ser(int id, String name) {
this.id = id;
this.name = name;
}
}
class Pser{
public static void main(String[] args)throws Exception {
Ser s1 = new Ser(211,"Najathi");
FileOutputStream fout = new FileOutputStream("fs.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("Success..");
}
}
Java Deserialization Code..
package com.najathi.www;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class DeSer implements Serializable {
int id;
String name;
public Ser(int id, String name) {
this.id = id;
this.name = name;
}
}
class Dser{
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("fs.txt"));
Ser s = (Ser)in.readObject();
System.out.println(s.id + " "+s.name );
in.close();
}
}
No comments:
Post a Comment