我想創建一個'添加帳戶'應用程序。我創建了一個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'。 –