附加文本文件

时间:2016-04-09 13:59:20

标签: java swing actionlistener bufferedwriter

我有这个代码将文本字段中的值打印到文件中。但是,我如何调整我的代码以重复地将文本附加到Java中的现有文件中。

                JButton submitInvoice = new JButton ("Submit");
            sPanel.add(submitInvoice);
            submitInvoice.addActionListener(e8->{
                try{
                    BufferedWriter bw = new BufferedWriter(new FileWriter("RegInvoice_0to2.txt",true));
                        bw.write("---------------Booking Invoice---------------");
                        bw.write("\r\n");
                        bw.write("All Day: "); bw.write(tSesh1.getText());
                        bw.write("\r\n");
                        bw.write("Morning: "); bw.write(tSesh2.getText());
                        bw.write("\r\n");
                        bw.write("Lunch: "); bw.write(tSesh3.getText());
                        bw.write("\r\n");
                        bw.write("Afternoon: "); bw.write(tSesh4.getText());
                        bw.write("\r\n");
                        bw.write("Pre School: "); bw.write(tSesh5.getText());
                        bw.write("\r\n");
                        bw.write("Full Holiday Care: "); bw.write(tSesh6.getText());
                        bw.write("\r\n");
                        bw.write("----------------Total Amount----------------");
                        bw.write("\r\n");

                        bw.close();
                }catch(Exception ex){
                    ex.printStackTrace();
                }

            });

1 个答案:

答案 0 :(得分:0)

您可以使用:

try(FileWriter fw = new FileWriter("outfilename", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

如果你多次写一个文件,bufferedWritter会更好。 否则,您可以找到更简单的实现。

来源:How to append text to an existing file in Java