Well today I had to serialize and deserialize an object. Turns out to be pretty simple actually. So I wanted to create a single example for future reference. All the examples I found were in two parts or were incomplete. So this example does everything in one example.
I create a Phone
object and serialize it. Then I change the data in the object. Next, the old object is read back and compared to the changed object. The output should be something like this.
Phone Entry: John Doe - 555-1212
Phone Entry: John Doe - 111-1111
Phone Entry: John Doe - 555-1212
Here is the source. I used static factory methods to create the objects. Trying to practice good habits.
1 import java.io.*;
2
3 public class SerialTest{
4 PrintWriter pw = new PrintWriter(System.out, true);
5
6 public static void main(String[] args) {
7 Phone phone01 = Phone.getNewPhone("John Doe", "555-1212");
8 Phone phone02 = Phone.getBlankPhone();
9
10 phone01.printNumber(); // Print start value
11
12 try {
13 ObjectOutputStream out = new ObjectOutputStream(
14 new FileOutputStream("object.dat"));
15 out.writeObject(phone01); // Serialize Object
16 out.close();
17 } catch(Exception e){
18 e.printStackTrace();
19 }
20
21 phone01.setNumber("111-1111"); // Change Object
22
23 try {
24 ObjectInputStream in = new ObjectInputStream(
25 new FileInputStream("object.dat"));
26 phone02 = (Phone) in.readObject();
27 in.close();
28 } catch(Exception e){
29 e.printStackTrace();
30 }
31
32 phone01.printNumber(); // Print Changed Object
33 phone02.printNumber(); // Print Original Object
34
35 }
36 }
37
38 class Phone implements Serializable {
39 private String name;
40 private String number;
41
42 private Phone(){
43 this.name = "";
44 this.number = "";
45 }
46
47 private Phone(String name, String number){
48 this.name = name;
49 this.number = number;
50 }
51
52 public static Phone getNewPhone(String name, String number){
53 Phone newPhone = new Phone(name, number);
54 return newPhone;
55 }
56
57 public static Phone getBlankPhone(){
58 Phone newPhone = new Phone();
59 return newPhone;
60 }
61
62 public void setNumber(String number){
63 this.number = number;
64 }
65
66 public void printNumber(){
67 System.out.println("Phone Entry: " + this.name + " - " + this.number);
68 }
69
70 }