我想创建一个“添加帐户”应用程序。我创建了一个 ArrayList 并将其存储到一个文本文件中,但是,它只将一组数据写入文本文件。
例如:帐户名称:Joe 帐号:10 当我按下“保存”按钮时,它现在保存在文本文件中,但是当我创建新帐户时,例如:帐户名称:Ryan,帐号:20,第一个帐户我创建的已被覆盖。你能告诉我的代码有什么问题吗?
public class JFrameNewAccount extends javax.swing.JFrame {
ArrayList<String> al = new ArrayList<String>();
private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
ButtonGroup bg = new ButtonGroup();
bg.add(rad_savings);
bg.add(rad_checking);
al.add(txt_accountnumber.getText());
al.add((txt_accountname.getText()));
if (rad_savings.isSelected()) {
al.add(rad_savings.getText());
} else {
al.add(rad_checking.getText());
al.add(txt_initialbalance.getText());
if (rad_savings.isSelected()) {
al.add(txt_interestrate.getText());
} else {
al.add(txt_overdraft.getText());
}
String fileName = "bank.txt";
FileWriter file = null;
try {
file = new FileWriter(fileName);
PrintWriter pw = new PrintWriter(file);
for (String str : al) {
pw.println(str);
}
pw.flush();
System.out.println("Write successful...");
} catch (FileNotFoundException ex) {
System.out.println("File not found....");
} catch (IOException ex) {
Logger.getLogger(JFrameNewAccount.class.getName()).log(
Level.SEVERE, null, ex);
} finally {
try {
file.close();
} catch (IOException ex) {
Logger.getLogger(JFrameNewAccount.class.getName()).log(
Level.SEVERE, null, ex);
}
}
JOptionPane
.showMessageDialog(this, "Your accont has been created!");
txt_accountname.setText("");
txt_accountnumber.setText("");
txt_initialbalance.setText("");
txt_overdraft.setText("");
txt_interestrate.setText("");
bg.clearSelection();
txt_accountnumber.requestFocus();
}
}
}