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 |
import javax.swing.JOptionPane; |
8 |
|
9 |
/** |
10 |
This program tests serialization of a Purse object. |
11 |
If a file with serialized purse data exists, then it is |
12 |
loaded. Otherwise the program starts with a new purse. |
13 |
More coins are added to the purse. Then the purse data |
14 |
are saved. |
15 |
*/ |
16 |
public class PurseTest |
17 |
{ |
18 |
public static void main(String[] args) |
19 |
throws IOException, ClassNotFoundException |
20 |
{ |
21 |
Purse myPurse; |
22 |
|
23 |
File f = new File("purse.dat"); |
24 |
if (f.exists()) |
25 |
{ |
26 |
ObjectInputStream in = new ObjectInputStream |
27 |
(new FileInputStream(f)); |
28 |
myPurse = (Purse)in.readObject(); |
29 |
in.close(); |
30 |
} |
31 |
else myPurse = new Purse(); |
32 |
|
33 |
// add coins to the purse |
34 |
myPurse.add(new Coin(NICKEL_VALUE, "nickel")); |
35 |
myPurse.add(new Coin(DIME_VALUE, "dime")); |
36 |
myPurse.add(new Coin(QUARTER_VALUE, "quarter")); |
37 |
|
38 |
double totalValue = myPurse.getTotal(); |
39 |
System.out.println("The total is " + totalValue); |
40 |
|
41 |
ObjectOutputStream out = new ObjectOutputStream |
42 |
(new FileOutputStream(f)); |
43 |
out.writeObject(myPurse); |
44 |
out.close(); |
45 |
} |
46 |
|
47 |
private static double NICKEL_VALUE = 0.05; |
48 |
private static double DIME_VALUE = 0.1; |
49 |
private static double QUARTER_VALUE = 0.25; |
50 |
} |