FileWriter in Java

The FileWriter class is used to write a character based stream to the file. The FileWriter is derived from the OutputStream class and this will throw IOException.
The FileWriter constructor is not dependent on the file already existing. It will create the file before opening it for output when an object is created. If we try to open a read – only file, an IOException will be thrown.

Consider the following example that will write data from a character buffer to file, character by character by using FileWriter.

Example:

/**
From FileWriterExample.java
*/

import java.io.FileWriter;

/**
 *
 * @author JavaHotSpot
 */

public class FileWriterExample
{
  public static void main(String args[])
  {
      try
      {
        char ch[]={'T','h','i','s','i','s','e','x','a','m','p','l','e',
                   'o','f','F','i','l','e','R','e','d','e','r'};
        FileWriter fw = new FileWriter("C:\\file1.txt");
        for(int i=0;i<ch.length;i++)
        {
            fw.write(ch[i]);
        }
          fw.close();
         
          System.out.println("Done...!");
      }
      catch(Exception ex)
      {
         System.err.println(ex);
      }
  }
}


Output: