Java file-writing FAQ: How do I append text to the end of a text file in Java?
Solution
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));
If you want more information, the rest of this article explains the details of this solution.
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:
// JavaFileAppendFileWriterExample.java
// Created by https://alvinalexander.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 {
// --------------------
// APPEND MODE SET HERE
// --------------------
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 append);
--------------
This simple constructor indicates that you want to write to the file in append mode.
| this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Java append to file - Related links
There is much more content related to Java and the String class on the blog, including these posts: