How to write multiple times to a text file using PrintWriter

I know how to create PrintWriter

and I can take lines from my gui and print them to a text file.

I want to be able to use the same program and print to a file, adding text to the file instead of replacing everything that is already in the text file. How can I make it so that when I add more data to the text file, it prints on a new line each time?

Any examples or resources would be great.


source to share

3 answers

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
     } catch (IOException e) {


The second parameter to the constructor FileWriter

will point to add to file (as opposed to clearing the file).

Usage is BufferedWriter

recommended for the dear author (i.e. a FileWriter

), while using PrintWriter

gives you access to the println syntax you are probably used to from System.out.

But the wrapper BufferedWriter

and PrintWriter

are not strictly necessary.



PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));


The FileWriter constructor comes with an append attribute, if that's true you can add it to the file.

check it



Your PrintWriter is wrapping another writer, which is probably a FileWriter. When you create this FileWriter, use a constructor that accepts both a File object and an "append" flag. If you pass true as the append flag, it will open the file in append mode, which means that new output will go at the end of the file's existing content, rather than overwriting the existing content.



All Articles