繁体   English   中英

(重写文本文件并保留以前的数据)获取值并每次在记事本文件的新行中写入记事本/ ms-word-

[英](re-writing the text file and keep previous data)get value and write in notepad/ms-word- every time in new line of notepad file

我知道如何从JTextField获取值并将其写入Java语言的文本文件中。 这是我的代码:

public class createfile {
    private Formatter x;

    public void openFile() {
        try {
            x = new Formatter("c:\\definition.txt");
        } catch (Exception e) {
            System.out.println("Error");
        }
    }

    private void addRecords() {
        x.format(null, jTextField3);
    }

    public void closFile() {
        x.close();
    }
}

它可以正常工作,并将jTextField3的值写入到名为“ definition.txt”的文件中。 但是,如果用户再次运行该程序,并在jTextField3中输入新值,则“ definition.txt”将填充新数据! 以前的数据将会丢失! 我不想那样! 我想保留每次用户输入的所有数据。 我应该如何更改代码? 谢谢 !

您想要附加到文件而不是覆盖它。 采用文件名的Formatter构造函数似乎无法胜任。 我建议您创建一个FileOutputStream ,在其中可以明确要求附加。 您可以将该流传递给Formatter构造函数,而不是原始文件名。

x = new Formatter(new FileOutputStream("c:\\definition.txt", true));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM