-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSerializationDemo2.java
More file actions
86 lines (76 loc) · 1.83 KB
/
Copy pathSerializationDemo2.java
File metadata and controls
86 lines (76 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
// Non-serializable Super class
class Employee{
private String name;
Employee(String name){
this.name = name;
}
@Override
public String toString(){
return name;
}
}
// A walkaround to solve the non-serializable super class
class SerEmployee implements Serializable{
private Employee emp;
private String name;
SerEmployee(String name){
this.name = name;
emp = new Employee(name);
}
private void readObject(ObjectInputStream ois) throws IOException{
name = ois.readUTF();
emp = new Employee(name);
}
private void writeObject(ObjectOutputStream oos) throws IOException{
oos.writeUTF(name);
}
@Override
public String toString(){
return name;
}
}
public class SerializationDemo2{
public static void main(String[] args){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try{
FileOutputStream fos = new FileOutputStream("employees.dat");
oos = new ObjectOutputStream(fos);
SerEmployee se = new SerEmployee("John Doe");
oos.writeObject(se);
System.out.println("se object writeten to file.");
oos.close();
oos = null;
FileInputStream fis = new FileInputStream("employees.dat");
ois = new ObjectInputStream(fis);
se = (SerEmployee)ois.readObject();
System.out.println("se object read from file.");
System.out.println(se);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
if(oos!=null){
try{
oos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
if(ois!=null){
try{
ois.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}
}