Java write to file

Write With FileWriter

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

public class JavaWriteToFileExample {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("Write With FileWriter.txt");
      myWriter.write("Writing something to file");
      myWriter.close();
      System.out.println("Done!");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}


Write With BufferedWriter

The advantage of using BufferedWriter is that it writes text to a character-output stream, buffering characters so as to provide for the efficient writing (better performance) of single characters, arrays, and strings.

Support for try-with-resources – introduced in Java 7 – allows us to declare resources to be used in a try block with the assurance that the resources will be closed when after the execution of that block.

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

public class JavaWriteToFileExample 
{
  public static void main(String[] args) 
  {
       // try-with-resources – introduced in Java 7
       try (FileWriter writer = new FileWriter("Write With BufferedWriter.txt");
             BufferedWriter bw = new BufferedWriter(writer)) 
       {

            bw.write("Write With BufferedWriter Example");
       } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
       }
       System.out.println("Done!");
  }
}


Write With PrintWriter
Write With FileOutputStream
Write With DataOutputStream
Write With RandomAccessFile
Write With FileChannel
Write With Files Class
Write to a Temporary File