FileWriter Write String into File in Java - Java @ Desk

Saturday, March 29, 2014

FileWriter Write String into File in Java

FileWriter Write String into 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.

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

This implementation will over write the content in the file. If you want to append the content to end of existing file click FileWriter Append String to End of Existing File in Java

Client Code -

package test;

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

public class FileWriterWrite {

 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); // This will create new file if it does not exists
   fileWriter.write("Write this to file");
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileWriter.close();
  }
 }
}






No comments:

Post a Comment