In this tutorial, I will show you how to write java program to write to a file. We will use the class FileWriter and BufferedWriter to write to a file.

Why we use FileWriter?

The FileWriter is a class used for writing character files. FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream. The constructors of FileWriter class assume that the default character encoding and the default byte-buffer size are acceptable.

Note that some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. Well in this situation, the constructors in this class will fail if the file involved is already open.

Then, why we use BufferedWriter too?

The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. In this tutorial, we don’t need to specify the buffer size.

Ok, now here is the code of java program to write text to a file:

import java.io.*;

public class FileWrite{
 public static void main(String args[]){
  try{
   // Create file
   FileWriter fstream = new FileWriter("out.txt");
   BufferedWriter out = new BufferedWriter(fstream);
   // Write to file
   out.write("Hello Java");
   //Close the output stream
   out.close();
  }catch (Exception e){ //Catch exception if any
   System.err.println("Error: " + e.getMessage());
  }
 }
}