1 | import java.io.IOException; |
2 | import java.io.RandomAccessFile; |
3 | |
4 | /** |
5 | This class is a conduit to a random access file |
6 | containing savings account data. |
7 | */ |
8 | public class BankData |
9 | { |
10 | /** |
11 | Constructs a BankData object that is not associated |
12 | with a file. |
13 | */ |
14 | public BankData() |
15 | { |
16 | file = null; |
17 | } |
18 | |
19 | /** |
20 | Opens the data file. |
21 | @param filename the name of the file containing savings |
22 | account information. |
23 | */ |
24 | public void open(String filename) |
25 | throws IOException |
26 | { |
27 | if (file != null) file.close(); |
28 | file = new RandomAccessFile(filename, "rw");; |
29 | } |
30 | |
31 | /** |
32 | Gets the number of accounts in the file. |
33 | @return the number of accounts. |
34 | */ |
35 | public int size() |
36 | throws IOException |
37 | { |
38 | return (int)(file.length() / RECORD_SIZE); |
39 | } |
40 | |
41 | /** |
42 | Closes the data file. |
43 | */ |
44 | public void close() |
45 | throws IOException |
46 | { |
47 | if (file != null) file.close(); |
48 | file = null; |
49 | } |
50 | |
51 | /** |
52 | Reads a savings account record. |
53 | @param n the index of the account in the data file |
54 | @return a savings account object initialized with the file data |
55 | */ |
56 | public SavingsAccount read(int n) |
57 | throws IOException |
58 | { |
59 | file.seek(n * RECORD_SIZE); |
60 | double balance = file.readDouble(); |
61 | double interestRate = file.readDouble(); |
62 | SavingsAccount account = new SavingsAccount(interestRate); |
63 | account.deposit(balance); |
64 | return account; |
65 | } |
66 | |
67 | /** |
68 | Writes a savings account record to the data file |
69 | @param n the index of the account in the data file |
70 | @param account the account to write |
71 | */ |
72 | public void write(int n, SavingsAccount account) |
73 | throws IOException |
74 | { |
75 | file.seek(n * RECORD_SIZE); |
76 | file.writeDouble(account.getBalance()); |
77 | file.writeDouble(account.getInterestRate()); |
78 | } |
79 | |
80 | private RandomAccessFile file; |
81 | |
82 | public static final int DOUBLE_SIZE = 8; |
83 | public static final int RECORD_SIZE |
84 | = 2 * DOUBLE_SIZE; |
85 | } |