Java: How to append text to a file with the FileWriter class

Java file writing FAQ: How do I append text to the end of a text file in Java?

The short answer is that you create a FileWriter instance with the append flag set to true, like this:

BufferedWriter bw = 
    new BufferedWriter(new FileWriter("checkbook.dat", true));

The rest of this article explains this.

A sample data file

To look at how to append text to the end of a file in Java, let's suppose you have a file named checkbook.dat that you want to append data to. Suppose checkbook.dat currently contains these two entries:

398:08291998:Joe's Car Shop:101.00
399:08301998:Papa John's Pizza:16.50

You can easily append data to the end of the text file by using the Java FileWriter and BufferedWriter classes. In particular, the most important part of the solution is to invoke the FileWriter constructor in the proper manner.

An “Append to file” example

Here's a sample mini-application that appends data to the end of the checkbook.dat data file. Pay attention to the way the FileWriter constructor is invoked:

//  Created by


public class JavaFileAppendFileWriterExample {

   public static void main (String[] args) {

      JavaFileAppendFileWriterExample a = new JavaFileAppendFileWriterExample();

   } // end main

   public void appendToCheckbook () {

      BufferedWriter bw = null;

      try {
         // -------------------- 
         // --------------------
         bw = new BufferedWriter(new FileWriter("checkbook.dat", true));
	 bw.write("400:08311998:Inprise Corporation:249.95");
      } catch (IOException ioe) {
      } finally {                       // always close the file
	 if (bw != null) try {
	 } catch (IOException ioe2) {
	    // just ignore it
      } // end try/catch/finally

   } // end test()

} // end class

The Java FileWriter constructor is called like this:

new FileWriter(String s, boolean append);

This simple constructor indicates that you want to write to the file in append mode.

Java append to file - Related links

There is much more content related to Java and the String class on the blog, including these posts: