Java program to write to text file

Let’s learn java program to write to text file.

Java program to write to text file

To write into a text file use FileWriter class. This class Writes text to character files using a default buffer size.

Encoding from characters to bytes uses either a specified charset or the platform’s default charset. Let’s see java code to write to a text file.

Here’s the java program to write into a text file.

import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteIntoTextFile 
{
   public static void main(String[] args)
   {
      try
      {    
         FileWriter fw = new FileWriter("B:\\demo.txt");    
         fw.write("Hello World");    
         fw.close();    
      }
      catch(Exception ex)
      {
         System.out.println(ex);
      }    
      System.out.println("Successful");
   }
}


Output:

Successful

demo.txt:

Hello World


Also read – classes and objects in java