java - 使用文件编写器时,如何在每次保存而不是覆盖以前的保存时使文本进入新行?
问题描述
正如标题所说,我试图让文件编写器在每次单击保存按钮时写入一个新行,而不是覆盖之前保存在文件中的任何内容。
代码:
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);
}
});
}
解决方案
正如评论中所指出的,您应该尝试配置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
推荐阅读
- hibernate - 如何只用 hql 映射一个实体
- python - Selenium WebDriver - 无法在 iFrame 中找到某些元素
- optimization - AMPL 向集合中的项目添加最小最大约束
- javascript - 如何从 Enzyme 中获取 React 儿童
- debugging - Prolog:调试递归源删除算法
- machine-learning - SpaCy NER 区分数字或实体
- xna - 2D 水凹凸贴图 - Monogame
- java - 如何在Android约束布局中均匀分布对象?
- factory-boy - 有没有办法让 FactoryBoy 将参数传递给我的 Django 模型的 save() 方法?
- angular - 角垫复选框性能问题