how to write to .txt in java code example

Example 1: Java program to write to text file

// Java program to write to 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");
   }
}

Example 2: writing to a text file java

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Tags:

Java Example