Java file writing FAQ: How do I append data to the end of a text file in Java?
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.
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:
// JavaFileAppendFileWriterExample.java // Created by http://www.devdaily.com import java.io.*; public class JavaFileAppendFileWriterExample { public static void main (String[] args) { JavaFileAppendFileWriterExample a = new JavaFileAppendFileWriterExample(); 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 Java FileWriter constructor is called like this:
new FileWriter(String s, boolean <i>append</i>);
This simple constructor indicates that you want to write to the file in append mode.
There is much more content related to Java and the String class on the blog, including these posts:
Post new comment