The fact that PrintWriter's method is called append() doesn't mean that it changes mode of the file being opened.

You need to open file in append mode as well:

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"), 
    true /* append = true */)); 

Also note that file will be written in system default encoding. It's not always desired and may cause interoperability problems, you may want to specify file encoding explicitly.

Answer from axtavt on Stack Overflow
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 637179 โ€บ java โ€บ Appending-Existing-File-Overwriting
Appending to an Existing File instead of Overwriting It [Solved] (I/O and Streams forum at Coderanch)
July 24, 2014 - Yes, FileWriter has a constructor which you can pass a filename and a boolean value in as a second parameter. If you pass in 'true' it will append to an existing file. ... Kevin Simonson wrote:But when I call the constructor for {PrintWriter} up above, it overwrites whatever the original contents ...
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2014 โ€บ 01 โ€บ how-to-append-to-a-file-in-java
How to append to a file in java using BufferedWriter, PrintWriter
import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo2 { public static void main( String[] args ) { try{ File file =new File("C://myfile.txt"); if(!file.exists()){ file.createNewFile(); } FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //This will add a new line to the file content pw.println(""); /* Below three statements would add three * mentioned Strings to the file in new lines.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ i/o โ€บ appending to a file in java
Appending to a File in Java
April 22, 2022 - To append a string to an existing file, open the writer in append mode and pass the second argument as true. String textToAppend = "Happy Learning !!"; Strinng filePath = "c:/temp/samplefile.txt"; try(FileWriter fw = new FileWriter(filePath, ...
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-append-to-file
Java append to file | DigitalOcean
August 3, 2022 - ... If you are working on text ... huge, you should use the BufferedWriter. To append binary or raw stream data to an existing file, you should use FileOutputStream....
๐ŸŒ
Net Informations
net-informations.com โ€บ java โ€บ cjava โ€บ append.htm
How to append text to an existing file in Java
Java append/add something to an existing file In Java, you can use PrintWriter(file,true) to append new content to the end of a file and this will keep the existing content and append the new content to the end of a file.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ java โ€“ append data to a file
Java โ€“ Append Data to a File | Baeldung
January 16, 2024 - Similarly, the FileOutputStream constructor accepts a boolean that should be set to true to mark that we want to append data to an existing file. Next โ€“ we can also append content to files using functionality in java.nio.file โ€“ which was introduced in JDK 7:
๐ŸŒ
Java67
java67.com โ€บ 2015 โ€บ 07 โ€บ how-to-append-text-to-existing-file-in-java-example.html
How to append text to existing File in Java? Example | Java67
Just write content using the println() method of PrintWriter. The resource will be closed automatically when the control will leave the try block. If there is any exception thrown from the try block then that will be suppressed.
Find elsewhere
Top answer
1 of 16
929

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

Java 7+

For a one-time task, the Files class makes this easy:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        StandardOpenOption.CREATE, StandardOpenOption.APPEND
    );
}

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:

try(FileWriter fw = new FileWriter("myfile.txt", 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
}

Notes:

  • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Older Java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}
2 of 16
203

You can use fileWriter with a flag set to true , for appending.

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
๐ŸŒ
Processing Forum
forum.processing.org โ€บ two โ€บ discussion โ€บ 8840 โ€บ how-to-append-a-new-line-of-text-to-an-existing-text-file.html
how to append a new line of text to an existing text file - Processing 2.x and 3.x Forum
December 31, 2014 - // append a new line to an exisiting text file import java.io.FileWriter; import java.io.BufferedWriter; void setup() { // // method A // // text file must be put in the sketch's local data folder // try { // // method A-1: // String path = dataPath("test.txt"); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(path, true))); // //// // method A-2: //// File f = dataFile("test.txt"); //// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true))); // // out.println("\n"); // out.println("hello"); // out.flush(); // out.close(); // } // catch (IOExceptio
๐ŸŒ
YouTube
youtube.com โ€บ shukri abo tteen
Writing and Appending to Text Files in Java | PrintWriter | FileWriter - YouTube
In this video we will see how we can use a file writer and a print writer to write and append text files.
Published ย  April 29, 2020
Views ย  6K
๐ŸŒ
Roy Tutorials
roytuts.com โ€บ home โ€บ java โ€บ write or append to a file using java
Write Or Append To A File Using Java - Roy Tutorials
November 9, 2023 - So, if file does not exist with same name then a file will be created for writing, and if a file exists then new data will be appended to the existing content of the file. CopyCollapse ยท package com.roytuts.java.write.append.data.file; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; public class FileApp { public static void main(String[] args) throws IOException { writeAppendToFile(null); } public static void writeAppendToFile(final String fileName) throws IOException { String out
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 26504146 โ€บ java-printwriter-doesnt-append-to-existing-txt-file-after-closing
Java PrintWriter doesn't append to existing .txt file after closing - Stack Overflow
If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object. ... When I look at the file nothing has been changed, no lines were added. There are not continuous lines, I just have to add a blank line and a test line. ... What output do you get? Are you sure you are writing the name/path of the file right? The code works for me. Here is the link This code appends to a file 'a' in the same place as the moja.java file.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 277696 โ€บ java โ€บ append-method-PrintWriter
append method of PrintWriter (I/O and Streams forum at Coderanch)
December 2, 2005 - All the PrintWriter convenience constructors that take a File or filename as an argument truncate any existing file to zero length. If you want to open the file for appending, you have to explicitly open it in "append" mode: PrintWriter pw = new PrintWriter(new FileWriter("a.txt", true));