Doing exam prep for college (Java OOP) and am really stumped on something. Any help would be appreciated. During the year I missed most of the I.O section (major mistake). Anyway, I shall try explain my problem best I can.
My application uses a swing UI and users should be able to create a bank account with a name, number and balance (String int and double). I am using an Account class to set, get and store variables.
I need functionality to add a new account, view all accounts, and then store all customer details in a file and be able to read them after the application is re-opened. Im using an ArrayList to store ArrayList<Account> accList;
and here is what I've come up with so far for writing the objects to file (I have the relevant FileHandling code already in so I'm not going to include the catch statements) :
Account account = new Account(name, number, balance);
accList.add(account);
try {
ObjectOutputStream out;
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(output)));
for (int i = 0; i < accList.size(); i++) {
out.writeObject(accList.get(i));
}
out.close();
}
Seems to work fine.. its the viewing from file I seem to have a problem with. Here is a code segment:
ObjectInputStream in = null;
Account account;
try {
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(output)));
while (true) {
account = (Account) in.readObject();
accList.add(account);
jTextArea1.setText(accList.toString());
}
The toString() method is my own @Override method in the Account class and prints the names fine. The poblem occurs when I press "view accounts" twice. It re-prints the output viewed everytime, so if there was 1 Account when first viewed, the next time it would be 2, then 3 etc. I know for such a long-winded question theres probably a simple answer but I have been looking at it for ages now and need another perspective!