-
Notifications
You must be signed in to change notification settings - Fork 7
/
ObjectStreamTest.java
79 lines (74 loc) · 2.19 KB
/
ObjectStreamTest.java
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
package com.corejava.chapter1;
import java.io.*;
import static java.lang.System.*;
public class ObjectStreamTest
{
public static void main(String[] args) throws Exception
{
Orientation original = Orientation.HORIZONTAL;
Orientation saved;
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.dat")))
{
oos.writeObject(original);// writing over.
}
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.dat"));)
{
saved = (Orientation) ois.readObject();
}
if(saved == Orientation.HORIZONTAL)
{
out.println("bingo");
}
else
{
out.println("Error");
}
}
public static void main1(String[] args) throws IOException, ClassNotFoundException
{
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
carl.setSecretary(harry);
Manager tony = new Manager("Tony Tester", 40000, 1990, 3, 15);
tony.setSecretary(harry);
Employee[] staff = new Employee[3];
staff[0] = carl;
staff[1] = harry;
staff[2] = tony;
// save all employee records to the file employee.dat
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat")))
{
out.writeObject(staff);
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat")))
{
// retrieve all records into a new array
Employee[] newStaff = (Employee[]) in.readObject();
// raise secretary's salary
newStaff[1].raiseSalary(10);
// print the newly read employee records
for (Employee e : newStaff)
System.out.println(e);
}
}
}
class Orientation implements Serializable
{
private int value;
public static final Orientation HORIZONTAL = new Orientation(1);
public static final Orientation VERTICAL = new Orientation(2);
private Orientation(int value)
{
this.value = value;
}
protected Object readResolve() throws ObjectStreamException
{
if(value == 1){
return Orientation.HORIZONTAL;
}else if(value == 2){
return Orientation.VERTICAL;
}else{
return null;
}
}
}