Java FileWriter - 追加文本文件行
我在 GUI 中有一个按钮,按下该按钮时,用户可以将信息添加到文本文件中。我已经将这部分设置得很好,但让我困惑的是,当用户写入文件时,它会删除文本文件中的所有信息,剩下的唯一一行是刚刚添加的新行。我需要添加信息并仍将原始信息保留在文本文件中。我认为追加命令能够做到这一点,但我显然做错了什么。任何帮助都会很棒!
这是我的代码:
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
writer.append(javax.swing.JOptionPane.showInputDialog(this, "add info"));
writer.newLine();
writer.close();
} catch (Exception e) {
}
I have a button in a GUI, and when the button is pressed the user has the ability to add information to a text file. I have this part setup fine, but the thing that is messing with me is that when the user writes to the file it erases all the info in the text file and the only line left is the new one that was just added. I need to add the information and still keep the original info in the text file. I thought the append command was able to do this, but I'm obviously doing something wrong. Any help would be awesome!
Here's my code:
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
writer.append(javax.swing.JOptionPane.showInputDialog(this, "add info"));
writer.newLine();
writer.close();
} catch (Exception e) {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用带有
bool append
参数的构造函数。请参阅FileWriter
为此。Use the constructor that takes a
bool append
parameter. See the javadocs forFileWriter
for that.您需要 writer.flush()。
PrintWriter
默认情况下会自动刷新,但Writers
不会You need
writer.flush()
.PrintWriter
are auto flush by default but notWriters