FileWriter Append String to End of Existing File in Java - Java @ Desk

Monday, March 31, 2014

FileWriter Append String to End of Existing File in Java

FileWriter Append String to End of Existing File in Java

java.io.FileWriter class is used to write string into a file in java. If the file does not exists at the path provided, FileWriter class first creates the new file.

With FileWriter, no need to check if File exists and no need to create the file.

The constructor takes the java.io.File object and creates the new file.

There are two constructons for FileWriter class
1) FileWriter(file) - Content is over written
2) FileWriter(file, boolean append) - If append is true then content is appended

If boolean append is true, then the content is appended to the file else the content is over written

Its very important to call the close() method on the FileWriter otherwise contents will not be written to the file created.

Client Code -

package test;

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

public class FileWriterAppendWrite {

 public static void main(String args[]) throws IOException {
  FileWriter fileWriter = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileWriter = new FileWriter(file, true); // This will append the content to file
   fileWriter.write("This is the appended text");
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileWriter.close();
  }
 }
}






No comments:

Post a Comment