Java FileWriter - 追加文本文件行

发布于 2024-10-31 20:59:17 字数 535 浏览 5 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傲鸠 2024-11-07 20:59:17

使用带有 bool append 参数的构造函数。请参阅 FileWriter 为此。

fWriter = new FileWriter("info.txt", true);

Use the constructor that takes a bool append parameter. See the javadocs for FileWriter for that.

fWriter = new FileWriter("info.txt", true);
守不住的情 2024-11-07 20:59:17

您需要 writer.flush()。 PrintWriter 默认情况下会自动刷新,但 Writers 不会

You need writer.flush(). PrintWriter are auto flush by default but not Writers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文