Writing Text Files in Java using FileWriter class

You are currently viewing Writing Text Files in Java using FileWriter class

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");
                 }
            }            
      }
}
READ ALSO:  Using DriveInfo class in VB.NET to get System Drives Information

Leave a Reply