Appending to a File in Java

Learn to append the data to a file in Java using BufferedWritter, PrintWriter, FileOutputStream and Files classes. In all the examples, while opening the file to write, we have passed a second argument as true which denotes that the file needs to be opened in append mode.

1. Using NIO Files

With Files class, we can write a file using it’s write() function. Internally write() function uses OutputStream to write byte array into the file.

To append content to an existing file, Use StandardOpenOption.APPEND while writing the content.

String textToAppend = "Happy Learning !!";

Path path = Paths.get("c:/temp/samplefile.txt");

Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND); 

2. Using BufferedWriter

BufferedWriter buffers the data in an internal byte array before writing to the file, so it results in fewer IO operations and improves the performance.

To append a string to an existing file, open the writer in append mode and pass the second argument as true.

String textToAppend = "Happy Learning !!";
Strinng filePath = "c:/temp/samplefile.txt";

try(FileWriter fw = new FileWriter(filePath, true);
BufferedWriter writer = new BufferedWriter(fw);) {

  writer.write(textToAppend);
}  

3. Using PrintWriter

We can use the PrintWriter to write formatted text to a file. PrintWriter implements all of the print() methods found in PrintStream, so we can use all formats which you use with System.out.println() statements.

To append content to an existing file, open the writer in append mode by passing the second argument as true.

String textToAppend = "Happy Learning !!";
String fileName = "c:/temp/samplefile.txt";

try(FileWriter fileWriter = new FileWriter(fileName, true);
PrintWriter printWriter = new PrintWriter(fileWriter);) {
  
  printWriter.println(textToAppend);
}

4. Using FileOutputStream

Use FileOutputStream to write binary data to a file. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true.

String textToAppend = "\r\n Happy Learning !!"; 
String fileName = "c:/temp/samplefile.txt";

try(FileOutputStream outputStream 
  = new FileOutputStream(fileName, true)) {
  
  byte[] strToBytes = textToAppend.getBytes();
  outputStream.write(strToBytes);
}

Happy Learning !!

Source Code on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Appending to a File in Java”

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.