Java Program to Append Text to an Existing File

Object Oriented ProgrammingJava8Java Programming

The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. To add contents to a file −

  •  Instantiate the BufferedWriter class.
  •  By passing the FileWriter object as an argument to its constructor.
  •  Write data to the file using the write() method.

Example

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileExample {
   public static void main( String[] args ) {

      try {
         String data = " Tutorials Point is a best website in the world";
         File f1 = new File("C:\Users\files\abc.txt");
         if(!f1.exists()) {
            f1.createNewFile();
         }

         FileWriter fileWritter = new FileWriter(f1.getName(),true);
         BufferedWriter bw = new BufferedWriter(fileWritter);
         bw.write(data);
         bw.close();
         System.out.println("Done");
      } catch(IOException e){
         e.printStackTrace();
      }
   }
}

Output

Done
raja
Published on 26-Apr-2018 11:32:21
Advertisements