Java Program to Append Text to an Existing File



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
Updated on: 2020-03-13T12:39:44+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements