我想创建一个'添加帐户'应用程序。我创建了一个ArrayList并将它存储到一个文本文件中,但是,它只将一组数据写入文本文件。ArrayList仅覆盖而不添加数据
例如:账户名称:乔 帐户号码:10 当我按下“保存”按钮,它现在保存在文本文件,但是当我创建一个新的accont,例如:开户名称:瑞安,账户号码: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();
}
}
}
你在哪里声明了'List'?要追加到现有文件,您需要具有'file = new FileWriter(fileName.true);'。 – NINCOMPOOP
你试过调试程序吗?确保数据**附加**到文件内容。我还建议分离责任,以便您可以拥有更易维护的代码,以便更容易发现问题。 ** [这](http://www.e-reading-lib.org/bookreader.php/134601/Clean_Code_-_A_Handbook_of_Agile_Software_Craftsmanship.pdf)**书可以帮助改善代码质量。 – Powerslave
关于代码的一般注意事项:如果'FileWriter'构造函数抛出并抛出'IOException',那么在'finally'块中关闭Writer的方式可能会导致您的程序崩溃并导致'NullPointerException'。 –