Writing a Text File in Java

Java has plenty of classes for file manipulation. For simple text files which contains lines of text, the best classes to use are FileWriter and PrintWriter in java.io package. PrintWriter has the method println() which writes a string into the file followed by a new line. Also note that PrintWriter and FileWriter must be closed in that order for the data to be actually written in the file. If you do not close PrintWriter or FileWriter, you may find that the resulting file is empty. FileWriter may throw checked exception IOException in case of any runtime error.

The following program demonstrates how you can write a text file in Java.

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;


/** Writing a text file Java.
 * 
 * @author jj
 */
public class WriteFile {
   
    public static void main(String[] args) {
        
        // data to write in file
        String data = "Hello World!";
        try {
            // Change this to a valid directory and file name in your system
            FileWriter fw = new FileWriter("/Volumes/ZEN/temp/test.txt");
            PrintWriter pw = new PrintWriter(fw);
            
            pw.println(data);
            
            pw.close();
            fw.close();
            
        }catch(IOException ex){
            System.out.println("Unable to write file!");
            ex.printStackTrace();
        }
        
    }
}