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
    }
}
Answer from Kip on Stack Overflow
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());
}
🌐
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)
Is there a way to call the constructor ... 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....
🌐
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.
🌐
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:
🌐
Attacomsian
attacomsian.com › blog › java-append-text-to-file
How to append text to a file in Java
December 7, 2019 - The second argument to the FileWriter constructor will tell it to append data to the file, rather than writing a new file. If the file does not already exist, it will be created.
🌐
Mkyong
mkyong.com › home › java › how to append text to a file in java
How to append text to a file in Java - Mkyong.com
October 1, 2020 - // append // if file not exists, create and write // if the file exists, append to the end of the file try (FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw)) { bw.write(content); bw.newLine(); // add new ...
🌐
W3Docs
w3docs.com › java
How to append text to an existing file in Java?
If you want to create a new file if it doesn't exist, or if you want to append to the file if it does, you can use the Files.exists() method to check whether the file exists, and then use the appropriate method:
Find elsewhere
🌐
CodeSignal
codesignal.com › learn › courses › fundamentals-of-text-data-manipulation-in-java-1 › lessons › writing-and-appending-text-files-in-java-1
Writing and Appending Text Files in Java
The content of the file after executing Files.write will look like this: ... Sometimes, you may want to add data to an existing file without overwriting its current contents. This can be easily achieved in Java using the Files.write method with the StandardOpenOption.APPEND flag.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-append-a-string-in-an-existing-file
Java Program to Append a String in an Existing File - GeeksforGeeks
July 11, 2025 - Now let us toggle onto methods of this class which is invoked here and play a crucial role in appending a string in an existing file as follows: ... This method closes the stream after flushing it. ... // Java Program to Append a String to the // End of a File // Importing input output classes import java.io.*; // Main class class GeeksforGeeks { // Method 1 // TO append string into a file public static void appendStrToFile(String fileName, String str) { // Try block to check for exceptions try { // Open given file in append mode by creating an // object of BufferedWriter class BufferedWriter
🌐
Techie Delight
techiedelight.com › home › java › append text to a file in java
Append text to a file in Java | Techie Delight
December 27, 2021 - We can use its asCharSink() method with APPEND mode, which appends data at the end of the file without truncating it. When no mode is provided, the file will be truncated before writing, or a new file is created when the target file doesn’t exist.
🌐
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. ... package com.roytuts.java.write.append.data.file; import java.io.File; import java.io.FileWriter; import java.io.IO...
🌐
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
You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using a special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true ...
🌐
codippa
codippa.com › home › append text to file in 7 ways in java
Append text to file in 7 ways in java - codippa
January 12, 2025 - This article will discuss 7 of those methods. Method 1: Using FileWriter java.io.FileWriter has a write() method which takes a string argument. This string argument is the content to be written to the file.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-append-to-file
Java append to file | DigitalOcean
August 3, 2022 - If the number of write operations is huge, you should use the BufferedWriter. To append binary or raw stream data to an existing file, you should use FileOutputStream. Here is the short program to append to file in java using FileWriter.
🌐
TutorialsPoint
tutorialspoint.com › Java-Program-to-Append-Text-to-an-Existing-File
Java Program to Append Text to an Existing File
March 13, 2020 - import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class AppendToFileExample { public static void main( String[] args ) { try { String data = " Tutorials Point is a best website in the world"; File f1 = new File("C:\Users\files\abc.txt"); if(!f1.exists()) { f1.createNewFile(); } FileWriter fileWritter = new FileWriter(f1.getName(),true); BufferedWriter bw = new BufferedWriter(fileWritter); bw.write(data); bw.close(); System.out.println("Done"); } catch(IOException e){ e.printStackTrace(); } } } Done ·
🌐
Stack Overflow
stackoverflow.com › questions › 60987454 › how-to-write-newfile-if-the-file-name-not-exist-and-append-file
java - how to write newfile if the file name not exist and append file? - Stack Overflow
April 2, 2020 - You can use java.time.LocalDate class to create the filename. If you want to append data if the file exists then you can send second parameter to the FileWriter object as true It opens the file in appending mode.
🌐
Programiz
programiz.com › java-programming › examples › append-text-existing-file
Java Program to Append Text to an Existing File
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class AppendFile { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; String text = "Added text"; try { Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { } } }