gpt4 book ai didi

java - ArrayList仅覆盖而不添加数据

转载 作者:行者123 更新时间:2023-12-01 18:48:15 25 4
gpt4 key购买 nike

我想创建一个“添加帐户”应用程序。我创建了一个 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();
}
}
}

最佳答案

似乎您的 FileWriter 每次都会覆盖输出文件。尝试 file = new FileWriter(fileName, true),这会将其置于追加模式并将数据添加到输出文件中。

关于java - ArrayList仅覆盖而不添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com