Hi, I am trying to enter a data from JtextField to notepad and need old data also in same notepad

huangapple go评论84阅读模式
英文:

Hi, I am trying to enter a data from JtextField to notepad and need old data also in same notepad

问题

在每次输入时,旧数据都会消失,只显示新数据。我希望同时显示新数据和旧数据。以下是我的代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    String abc = jTextField1.getText().toString();
    PrintWriter writer = null;
    try {
        writer = new PrintWriter("textFieldOutput.txt", "UTF-8");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
    writer.println(abc);
    writer.close();
}

如果你需要保留旧数据,你需要修改代码以追加而不是覆盖现有文件中的数据。

英文:

.In each entering the old data is disappearing and only new data is showing there. I want both datas new and the old data. here is my code.:

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
     String abc= jTextField1.getText().toString();
        PrintWriter writer = null;
        try {
            writer = new PrintWriter("textFieldOutput.txt", "UTF-8");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
writer.println(abc);
writer.close();
     }            

答案1

得分: 1

在每次输入时,旧数据会消失,只会显示新数据。

使用FileWriter代替PrintWriter

然后您可以以“追加”的模式打开文件。

阅读FileWriter API,以获取要使用的适当构造函数。

您还需要使用write(...)方法,而不是println(...)方法。

通常您还会将FileWriter包装在BufferedWriter中。然后,您可以根据需要使用newline()方法。

英文:

> In each entering the old data is disappearing and only new data is showing there.

Use a FileWriter instead of the PrintWriter.

Then you can open the file in "append" mode.

Read the FileWriter API for the appropriate constructor to use.

You will also need to use the write(...) method instead of the println(..) method.

Typically you would also wrap the FileWriter in a BufferedWriter. Then you can use the newline() method as required.

huangapple
  • 本文由 发表于 2020年8月26日 23:49:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63601214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定