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");
                 }
            }            
      }
}​

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments