FAQ: How do I append data to a file?

By Alvin J. Alexander, devdaily.com

Java FAQ: How do I append data to a file?

Appending text to a file using Java is actually very easy, just like writing to the file, with one minor change. All you have to do is add an extra boolean parameter when creating your FileWriter object, as shown in the example source code below. This extra parameter opens the file in "append" mode. You'll see that if you run this sample program several times the string "Hello, World" is appended to the file over and over.

package com.devdaily.javasamples;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Demonstrates how to append text to a file using Java.
 * (Just add a "true" boolean parameter when creating the FileWriter.)
 * Created by Alvin Alexander, http://devdaily.com.
 */
public class JavaAppendTextToAFileExample
{

  public static void main(String[] args) 
  {
    PrintWriter pw = null;
    try
    {
      // created as a separate variable to emphasize that I'm appending to this file
      boolean append = true;
      pw = new PrintWriter(new FileWriter(new File("/Users/al/HelloWorld.txt"), append));
      // a print writer gives you many more methods to write with
      pw.println("Hello, World");
    }
    catch (IOException e)
    {
      e.printStackTrace();
      // deal with the exception
    }
    finally
    {
      pw.close();
    }
  }

}

devdaily logo