Serialization: Object Serialization Explanation + Example of File + Network
Serialization: Object Serialization Explanation + Example of File + Network
address.txt
25-Oct-05
Serialization
Javas answer:
Serializable Interface
Serialization
Automatic Writing
System knows how to recursively write out the state of an object to stream
Automatic Reading
System knows how to read the data from Stream and re-create object in
memory
Downcasting is required
How it works?
ObjectInputStream in;
PersonInfo obj = (PersonInfo) in.readObject();
25-Oct-05
import javax.swing.*;
import java.io.*;
String name;
String address;
String phoneNum;
try {
FileOutputStream fos = new FileOutputStream("ali.dat");
ObjectOutputStream out = new ObjectOutputStream(fos);
//serialization
out.writeObject(pWrite);
out.close();
fos.close();
}
7
import java.io*;
public class ReadEx{
public static void main(String args[ ]){
try {
FileInputStream fis = new FileInputStream("ali.dat");
ObjectInputStream in = new ObjectInputStream(fis);
//de - serialization
PersonInfo pRead = (PersonInfo) in.readObject( );
pRead.printPersonInfo();
in.close();
fis.close();
} catch (Exception ex){
System.out.println(ex)
}
}
9
10
..
..
oos.write(p);
11
Socket s = ss.accept();
InputStream in = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
PersonInfo p = (PersonInfo) ois.read( );
12
Preventing Serailization
import javax.swing.*;
import java.io.*;
public class PersonInfo implements Serializable{
String name;
String address;
transient String phoneNum;
14
15