|
| 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