Skip to content

Commit 55b8d0b

Browse files
serialization is fun
1 parent a13228f commit 55b8d0b

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package learnHeadFirstJava.serializationIsFun;
2+
3+
import java.io.Serializable;
4+
5+
public class GospelBook implements Serializable {
6+
private static final long serialVersionUID = 3141633621593356035L;
7+
private String name;
8+
private String author;
9+
private int order;
10+
11+
public GospelBook(String name, String author, int order) {
12+
super();
13+
this.name = name;
14+
this.author = author;
15+
this.order = order;
16+
}
17+
public String getName(){
18+
return name;
19+
}
20+
public int getOrder(){
21+
return order;
22+
}
23+
public String getAuthor(){
24+
return author;
25+
}
26+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package learnHeadFirstJava.serializationIsFun;
2+
3+
import java.io.FileInputStream;
4+
import java.io.FileNotFoundException;
5+
import java.io.FileOutputStream;
6+
import java.io.IOException;
7+
import java.io.ObjectInputStream;
8+
import java.io.ObjectOutputStream;
9+
10+
public class GospelSaverTest {
11+
public static void main(String[] args) throws ClassNotFoundException {
12+
GospelBook matthew = new GospelBook("Matthew", "anonymous", 1);
13+
GospelBook mark = new GospelBook("Mark", "unknown", 2);
14+
GospelBook luke = new GospelBook("Luke", "not named", 3);
15+
GospelBook john = new GospelBook("John", "anonymous", 4);
16+
17+
try {
18+
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Gospel.ser"));
19+
os.writeObject(mark);
20+
os.writeObject(matthew);
21+
os.writeObject(luke);
22+
os.writeObject(john);
23+
os.close();
24+
} catch (FileNotFoundException e) {
25+
e.printStackTrace();
26+
} catch (IOException e) {
27+
e.printStackTrace();
28+
}
29+
john = null;
30+
matthew = null;
31+
luke = null;
32+
mark = null;
33+
34+
try {
35+
ObjectInputStream is = new ObjectInputStream(new FileInputStream("Gospel.ser"));
36+
GospelBook restore1 = (GospelBook) is.readObject();
37+
GospelBook restore2 = (GospelBook) is.readObject();
38+
GospelBook restore3 = (GospelBook) is.readObject();
39+
GospelBook restore4 = (GospelBook) is.readObject();
40+
System.out.println("restore1 name is: " + restore1.getName());
41+
System.out.println("restore2 name is: " + restore2.getName());
42+
System.out.println("restore3 name is: " + restore3.getName());
43+
System.out.println("restore4 cnamelass is: " + restore4.getName());
44+
} catch (FileNotFoundException e) {
45+
e.printStackTrace();
46+
} catch (IOException e) {
47+
e.printStackTrace();
48+
}
49+
System.out.println("Program ended.");
50+
}
51+
}

0 commit comments

Comments
 (0)