首页 > 解决方案 > 使用文件编写器时,如何在每次保存而不是覆盖以前的保存时使文本进入新行?

问题描述

正如标题所说,我试图让文件编写器在每次单击保存按钮时写入一个新行,而不是覆盖之前保存在文件中的任何内容。

代码:

saveButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try{
                PrintWriter fileWriter = new PrintWriter("passwords.txt", StandardCharsets.UTF_8);
                fileWriter.print(webApp.getText());
                fileWriter.print(": ");
                fileWriter.print(pass.getText());
                fileWriter.close();
            } catch (IOException b) {
                b.printStackTrace();
            }
            pass.setText(null);
            webApp.setText(null);
        }
    });
}

标签: java

解决方案


正如评论中所指出的,您应该尝试配置FileWriter为附加模式,如下所示:

private static void writeToFile(final String filePathName, String text) throws IOException {
    FileWriter fileWriter = new FileWriter(filePathName, true); // Set append=true
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.println(text);
    printWriter.close();
}

使用如下代码重复调用上述函数:

writeToFile("passwords.txt", "Some text");
writeToFile("passwords.txt", "Some More text");
writeToFile("passwords.txt", "Other text");

它将产生以下文件:

stackoverflow-code : $ cat passwords.txt 
Some text
Some More text
Other text

推荐阅读