1 import java.io.File;
2 import java.io.IOException;
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.ObjectInputStream;
6 import java.io.ObjectOutputStream;
7
8 /**
9 This program demonstrates serialization of a Bank object.
10 If a file with serialized data exists, then it is loaded.
11 Otherwise the program starts with a new bank.
12 Bank accounts are added to the bank. Then the bank
13 object is saved.
14 */
15 public class SerialDemo
16 {
17 public static void main(String[] args)
18 throws IOException, ClassNotFoundException
19 {
20 Bank firstBankOfJava;
21
22 File f = new File("bank.dat");
23 if (f.exists())
24 {
25 ObjectInputStream in = new ObjectInputStream(
26 new FileInputStream(f));
27 firstBankOfJava = (Bank) in.readObject();
28 in.close();
29 }
30 else
31 {
32 firstBankOfJava = new Bank();
33 firstBankOfJava.addAccount(new BankAccount(1001, 20000));
34 firstBankOfJava.addAccount(new BankAccount(1015, 10000));
35 }
36
37 // Deposit some money
38 BankAccount a = firstBankOfJava.find(1001);
39 a.deposit(100);
40 System.out.println(a.getAccountNumber() + ": " + a.getBalance());
41 a = firstBankOfJava.find(1015);
42 System.out.println(a.getAccountNumber() + ": " + a.getBalance());
43
44 ObjectOutputStream out = new ObjectOutputStream(
45 new FileOutputStream(f));
46 out.writeObject(firstBankOfJava);
47 out.close();
48 }
49 }