How to append text to an existing file in Java


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

    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
catch(IOException ioe)
    System.err.println("IOException: " + ioe.getMessage());

I need to append text repeatedly to an existing file in Java. How do I do that?

 * it will write content to a specified  file
 * @param keyString
 * @throws IOException
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
}// end of writeToFile()

You can also try this :

JFileChooser c= new JFileChooser();
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file

    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    raf.setLength(length + 1); //+ (integer value) for spacing;
catch (Exception e) {
    //any exception handling method of ur choice

If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
    } catch (IOException e) {

There are few points to note:

  1. It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets.
  2. The code uses try-with-resource statement in which resources are automatically closed after the try.

Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential we can make use of stream APIs in Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
} catch (IOException e) {

Edit - as of Apache Commons 2.1, the correct way to do it is:

FileUtils.writeStringToFile(file, "String to append", true);

I adapted @Kip's solution to include properly closing the file on finally:

public static void appendToFile(String targetFile, String s) throws IOException {
    appendToFile(new File(targetFile), s);

public static void appendToFile(File targetFile, String s) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(targetFile, true)));
    } finally {
        if (out != null) {


public class Writer {

    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");

    public static void doWrite(String filePath,String contentToBeAppended){

            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
        catch( IOException e ){
        // File writing/opening failed at some stage.



I just add small detail:

    new FileWriter("outfilename", true)

2.nd parameter (true) is a feature (or, interface) called appendable ( It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content

In other words, you can add some content to your gzipped file, or some http process

Sample, using Guava:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);

I might suggest the apache commons project. This project already provides a framework for doing what you need (i.e. flexible filtering of collections).

My answer:

JFileChooser chooser= new JFileChooser();
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);;
catch (Exception exception) {
    //exception handling

In Java-7 it also can be done such kind:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

Create a function anywhere in your project and simply call that function where ever you need it.

Guys you got to remember that you guys are calling active threads that you are not calling asynchronously and since it would likely be a good 5 to 10 pages to get it done right. Why not spend more time on your project and forget about writing anything already written. Properly

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
       return java.util.logging.Logger.getLogger("MyLogFileName");
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    /*********log file resides in server root log files********/

three lines of code two really since the third actually appends text. :P

This code will fulifil your need:

   FileWriter fw=new FileWriter("C:\\file.json",true);

Try with bufferFileWriter.append, it works with me.

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);