How to Append Content to File in Java

1. Overview

In Java, we can use FileWriter(file, true) to append new content to the end of a file.
  1. All existing content will be overridden.
new FileWriter(file);
  1. Keep the existing content and append the new content to the end of a file.
new FileWriter(file,true);

2. FileWriter – Append file example

  1. Let's create a file "sample.txt" under a directory "C:/workspace".
  2. Keep some content in file C:/workspace/sample.txt like
There is some content in file
  1. Let's Java example to append new content to the end of a file.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Java program demonstrates how to append content to existing file contents.
 * @author javaguides.net
 */

public class AppendFileExample {
 
 private static final Logger LOGGER = LoggerFactory
   .getLogger(AppendFileExample.class);
 
 public static void main(String[] args) {
  appendToExitingFile();
 }
 
 public static void appendToExitingFile(){
  try (Writer writer = new FileWriter("C:/workspace/sample.txt",true);
    BufferedWriter bw = new BufferedWriter(writer)) {
   String content = "append something to existing file\n";
   bw.write(content);
  } catch (IOException e) {
   LOGGER.error(e.getMessage());
  }
 }
}
Output: Let's open the "sample.txt" and verify the content.
There is some content in file append something to existing file
User Writer interface as reference type so it provides loose coupling. In the future, we may use some other Writer classes.

3. Reference 

https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Comments