Core Java Tutorial

Core Java Tutorial

How to Appending content to existing file in Java

FileWriter Appending :

FileWriter has the following constructor to append a content to existing file. Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Program

import java.io.FileWriter;

import java.io.IOException;

public class FileWriterExample {

 public static void main(String[] args) {


  try {

   FileWriter fw = new FileWriter("sam.txt", true);

   fw.write("Sample content to write in a file");

   fw.write("\n");

   fw.write("second line of a sam file");

   fw.flush();

   fw.close();

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

 }

}

Run the above program more than once to check the output.

true: file will get appended

false: file will get overwritten