forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializationDemo.java
More file actions
54 lines (51 loc) · 1.46 KB
/
Copy pathSerializationDemo.java
File metadata and controls
54 lines (51 loc) · 1.46 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
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class SerializationDemo{
private static final String FILE_PATH = "employee.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.writeInt(89757);
oos.close();
oos = null;
*/
FileInputStream fis = new FileInputStream(FILE_PATH);
ois = new ObjectInputStream(fis);
Employee emp;
emp = (Employee)ois.readObject();
System.out.println("Deserialization: " + emp.getName());
System.out.println("Deserialization: " + emp.getAge());
System.out.println("Deserialization: " + emp.getSalary()); // output 0 as default initial value.
System.out.println("Deserialization: " + emp.getBonus()); // transient field compatible: output 0.
System.out.println("BONUS: " + ois.readInt());
}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();
}
}
}
}
}