【问题标题】:How to add new line of text by button? [duplicate]如何通过按钮添加新的文本行? [复制]
【发布时间】:2016-10-13 21:12:05
【问题描述】:

我有一个公共方法,可以将文本字段中的一些文本添加到 .txt 文件中,尽管它只工作一次。 我希望该按钮在每次单击按钮时添加新的文本行(这样我们就可以更改文本字段中的文本并将其添加到新行...)。

    try {
        ncw = new PrintWriter("database.txt");
        ncw.write(nctext.getText());
        ncw.close();
    } catch (IOException ae) {
        System.out.println("IO Exception");
    }
}

我该怎么办?

【问题讨论】:

    标签: java button javafx printwriter bufferedwriter


    【解决方案1】:

    试试这个,第二个布尔参数告诉 FileWriter 是追加还是覆盖

    true = 附加模式

    false= 覆盖模式

    FileWriter fw = null;
    BufferedWriter bw = null;
    PrintWriter out = null;
    try{
    
            fw = new FileWriter("database.txt", true);
            bw = new BufferedWriter(fw);
            out = new PrintWriter(bw);
    
                        out.println(nctext.getText());
                        out.flush();
                        out.close();
    
    
       } catch (IOException e) {
                       e.printstacktrace();}                
    

    【讨论】:

    • 但这会删除现有文本
    • "true" 参数完全有效! THX
    • 如果你通过 true 它将以追加模式写入
    • @ItamarGreen 它
    • @ItamarGreen 抱歉,我刚刚不小心按了 Enter。它应该看起来像这样:try { ncw = new FileWriter("base.txt", true); ncbw = new BufferedWriter(ncw); ncbw.newLine(); ncbw.write(nctext.getText()); ncbw.newLine(); ncbw.close(); } catch (IOException ex) { System.out.println("IO 异常"); } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多