Sunday 24 June 2012

Append data to a text file in Java

One of the common task related to a text file is to append or add some contents to the file.We can do this in Java using a FileWriter class. This class has a constructor that accept a boolean parameter called append. By setting this value to true, it will keep the existing content and append the new content in the end of the file. I.e

new FileWriter(file)

  • Creates a new file if the specified file not exist.
  • If file already exist, erase the content and open it.

new FileWriter(file, true)

  • Creates a new file if the specified file not exist.
  • If file already exist, open it by keeping the existing content and                                               append the content at the end of the file.


Let us see an example :

The following code appends a new line at the end of an existing file append.txt


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

public class AppendDataToFile {

 /**
  * @param Pass
  * @throws IOException
  **/
 public static void main(String[] args) {

  BufferedWriter bw =null;

  try {
   FileWriter fr = new FileWriter("/home/radhakrishnan/Desktop/append.txt",true);

   bw= new BufferedWriter(fr);

   bw.write("Adding a new line at the end of file");
   bw.newLine();

  } catch (IOException e) {

   System.out.println(e);

  } finally {

   try {
    bw.close();

   } catch (IOException e) {

    e.printStackTrace();
   }
  }
 }
}

No comments:

Post a Comment