Learn Java: Java Q&A: How do I append data to the end of a text file with Java?
Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


Question: How do I append data to the end of a text file with Java?
Answer:  

The solution I'm presenting here works with Java JDK 1.1.x and more recent versions of the JDK. I haven't including a JDK 1.0.x solution, because our belief is that JDK 1.0.x is only used at this time for applets. Because applets *generally* cannot access a filesystem, there isn't much call for appending data to files. If anyone is interested in seeing how to append data to a text file with JDK 1.0.x, just send us an e-mail.

To answer this question, 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 FileWriter and BufferedWriter classes. In particular, the most important part of the solution is to invoke the FileWriter constructor in the proper manner.

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:

//  Append.java
//
//  Developer's Daily
//  http://www.DevDaily.com
//  Copyright 1998 DevDaily Interactive, Inc.  All Rights Reserved.

import java.io.*;

public class Append {

   //--------------------------------------------------//

   public static void main (String[] args) {

      Append a = new Append();
      a.appendToCheckbook();

   } // 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");
	 bw.newLine();
	 bw.flush();
      } catch (IOException ioe) {
	 ioe.printStackTrace();
      } finally {                       // always close the file
	 if (bw != null) try {
	    bw.close();
	 } catch (IOException ioe2) {
	    // just ignore it
	 }
      } // end try/catch/finally

   } // end test()

} // end class

The 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.

Note: This code has been tested on a SCO UnixWare 7 computer running Java JDK 1.1.3. It has not currently been tested on other platforms. Please let us know if you try this code on other platforms and experience any problems.

Click here to download the Append.java source code file.

 


Read the BLOG

Copyright © 1998-2002 DevDaily Interactive, Inc.
All Rights Reserved.