-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSerializationDemo3.java
More file actions
86 lines (74 loc) · 1.97 KB
/
Copy pathSerializationDemo3.java
File metadata and controls
86 lines (74 loc) · 1.97 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.Externalizable;
import java.io.ObjectOutput;
import java.io.ObjectInput;
public class SerializationDemo3{
private static final String FILE_PATH = "emps.dat";
public static void main(String[] args){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try{
FileOutputStream fos = new FileOutputStream(FILE_PATH);
oos = new ObjectOutputStream(fos);
Employee emp = new Employee("John Doe", 36);
oos.writeObject(emp);
oos.close();
oos = null;
FileInputStream fis = new FileInputStream(FILE_PATH);
ois = new ObjectInputStream(fis);
emp = (Employee)ois.readObject();
System.out.println("Deserialization: " + emp.getName());
System.out.println("Deserialization: " + emp.getAge());
}catch(IOException ioe){
ioe.printStackTrace();
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}finally{
if(oos != null){
try{
oos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
if(ois !=null){
try{
ois.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
}
}
class Employee implements Externalizable{
private String name;
private int age;
// No argument constructor is necessary for deserialization through Externalizable-oriented serialization mechanism.
public Employee(){
}
public Employee(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void writeExternal(ObjectOutput out) throws IOException{
System.out.println("writeExternal is called.");
out.writeUTF(name);
out.writeInt(age);
}
public void readExternal(ObjectInput in) throws IOException{
System.out.println("readExternal is called.");
this.name = in.readUTF();
this.age = in.readInt();
}
}