Java - Append text to file

By xngo on June 14, 2019

Here is how to append text or string into a file.

package net.openwritings.java.io;
 
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
 
public class AppendTextToFile {
 
    public static void main(String[] args) {
 
        try
        {
            final String filename="file.txt";
 
            // FileWriter(File file, boolean append): 
            //    Set append boolean to true to append text.
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
            writer.println("Some text to append");
            writer.close();
        }
        catch(IOException e)
        {
          e.printStackTrace();
        }
    }
}

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/io/AppendTextToFile.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.