Writing Text Files in Java using FileWriter class

Waqas Anwar
07 April 2008
10191 Views

Java IO package provides FileWriter class which developers can use to write contents in disk file as a sequence of characters. The constructor of the class requires file path and creates automatically if it does not exist depending on the user operation system security settings.

Following code shows how you can write a simple text file using FileWriter class.
import java.io.*;

public class FileWriterTest
{
      public static void main(String[] args)
      {
            String b = System.getProperty("line.separator");
            String path = "C:\\myfile.txt";
      
            FileWriter w = null;
            try
            {  
                  w = new FileWriter(path);  
   
                  w.write("File Contents Here...." + b);
                  w.write("File Contents Here...." + b);
                  w.write("File Contents Here...." + b);
    
                  w.flush();
                  System.out.println("File Written: " + path);
            }
            catch(IOException ex)
            {
                  System.out.println("File Writing Error");
            }
            finally
            {
                  try
                  {
                        w.close();
                  }
                  catch(IOException ex)
                  {
                        System.out.println("File Closing Error");
                 }
            }            
      }
}