1

I have this code that prints values in a text field to a file. But how would I adapt my code to append text repeatedly to an existing file in 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();
                }

            });
mKorbel
  • 109,525
  • 20
  • 134
  • 319
DeeMoMo
  • 35
  • 1
  • 6

1 Answers1

0

You can use this :

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
}

A bufferedWritter is better if you write many time to a file. Otherwise, you can find much simpler implementation.

Source : How to append text to an existing file in Java

Community
  • 1
  • 1
Dan S.
  • 36
  • 3