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
🌐
Baeldung
baeldung.com › home › java › java io › java – append data to a file
Java – Append Data to a File | Baeldung
January 16, 2024 - Next – we can also append content to files using functionality in java.nio.file – which was introduced in JDK 7:
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());
}
🌐
Greenfoot
greenfoot.org › topics › 65278 › 0
Greenfoot | Discuss | How to Append Text to an Existing File in Java
February 17, 2023 - public void read() { File file = new File("C:/Users/nnnvi/Documents/Greenfoot copy/CricketGame-copy/Highscore.txt"); try { lines = Files.readAllLines(file.toPath()); } catch(IOException e) { System.err.println("An exception occurred"); } theLines = lines.toArray(new String[0]); } public void write() { try { String text = Integer.toString(myScore); Path fileName = Path.of("C:/Users/nnnvi/Documents/Greenfoot copy/CricketGame-copy/Highscore.txt"); Files.writeString(fileName, text); }catch(IOException e) { System.err.println("An exception occurred"); } }
🌐
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
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-append-to-file
Java append to file | DigitalOcean
August 3, 2022 - Here is the short program to append to file in java using FileWriter.
🌐
W3Schools
w3schools.com › java › java_files.asp
Java Files
The File class from the java.io package, allows us to work with files.
🌐
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
In this lesson, we've covered the fundamental skills necessary for writing and appending text to files using Java's Files class. You have learned how to use Files.write to write data and append new content to existing files using StandardOpenOption.APPEND.
🌐
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.
Find elsewhere
🌐
Programiz
programiz.com › java-programming › examples › append-text-existing-file
Java Program to Append Text to an Existing File
The write() method takes the path of the given file, the text to the written, and how the file should be open for writing. In our case, we used APPEND option for writing. Since the write() method may return an IOException, we use a try-catch block to catch the exception properly. import java.io.FileWriter; import java.io.IOException; public class AppendFile { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; String text = "Added text"; try { FileWriter fw = new FileWriter(path, true); fw.write(text); fw.close(); } catch(IOException e) { } } }
🌐
Centron
centron.de › startseite › java append to file – tutorial
Appending Data to a File in Java – Best Methods
February 18, 2025 - A guide to appending text to a file in Java. Covers FileWriter, BufferedWriter, and Files.write() with practical examples.
🌐
CodeChef
codechef.com › learn › course › java › JAVANEW31 › problems › TWOLMM29
Appending Text/Lines to Files in Java in Java
Test your Learn Java knowledge with our Appending Text/Lines to Files in Java practice problem. Dive into the world of java challenges at CodeChef.
🌐
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.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date;
🌐
Medium
medium.com › @oofnivek › java-read-write-file-dff5ea60171f
Java Read/Write/Append File - Kevin FOO - Medium
January 11, 2024 - Reading a file line by line in Java. ... Writing a string to file. Join Medium for free to get updates from this writer. ... Appending string to file.
🌐
Sarthaks eConnect
sarthaks.com › 3495349 › how-can-i-append-to-a-file-in-java
How can I append to a file in Java? - Sarthaks eConnect | Largest Online Education Community
April 27, 2023 - LIVE Course for free · To append to a file in Java, you can use the FileWriter class with the append flag set to true
🌐
W3Schools
w3schools.com › java › java_files_write.asp
Java Write To Files
If you want to add new content at the end of the file (without deleting what's already there), you can use the two-argument constructor and pass true as the second parameter. This puts the writer into append mode: import java.io.FileWriter; ...
🌐
w3resource
w3resource.com › java-exercises › io › java-io-exercise-16.php
Java - Append text to an existing file
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; public class Exercise16 { public static void main(String a[]){ StringBuilder sb = new StringBuilder(); String strLine = ""; try { String filename= "/home/students/myfile.txt"; FileWriter fw = new FileWriter(filename,true); //appends the string to the file fw.write("Java Exercises\n"); fw.close(); BufferedReader br = new BufferedReader(new FileReader("/home/students/myfile.txt")); //read the file content while (strLine != null) { sb.append(strLine); sb.append(System.lineSeparator()); strLine = br.readLine(); System.out.println(strLine); } br.close(); } catch(IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); } } }
🌐
Home and Learn
homeandlearn.co.uk › java › write_to_textfile.html
java for complete beginners - writing to text files
Add the following line to create a new object from your WriteFile class: WriteFile data = new WriteFile( file_name , true ); So we've set up a WriteFile object called data. In between the round brackets of WriteFile, we've added two things: the name of the file, and an append value of true.
🌐
Verj
hub.verj.io › ebase › doc › javadocAPI › com › ebasetech › xi › services › FileServices.html
FileServices
Creates a new file if necessary with the specified file path and appends the specified text to the file. ... public static void appendToFile​(java.lang.String filePath, java.lang.String text, java.lang.String encoding) throws java.io.IOException
🌐
University of Edinburgh
www2.ph.ed.ac.uk › ~wjh › java › ptplot5.6-devel › doc › codeDoc › ptolemy › util › FileUtilities.html
FileUtilities
If the name begins with "$CLASSPATH" or "xxxxxxCLASSPATHxxxxxx", then the name is passed to nameToURL(String, URI, ClassLoader) If the file name is not absolute, the it is assumed to be relative to the specified base URI. ... classLoader - The class loader to use to locate system resources, or null to use the system class loader that was used to load this class. ... If the name is null or the empty string, then null is returned, otherwise a buffered reader is returned. ... public static java.io.Writer openForWriting(java.lang.String name, java.net.URI base, boolean append) throws java.io.IOException