store data into temporary file java

Example:

package com.w3schools;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
 
public class WriteStringToFileTest {
  public static void main(String args[]){
	  BufferedWriter bufferedWriter = null;
      try {
          String strContent = "Test Content";
          File myFile = new File("D:/Test files/test.txt");
          //check if file exist, 
          //otherwise create the file before writing
          if (!myFile.exists()) {
              myFile.createNewFile();
          }
          Writer writer = new FileWriter(myFile);
          bufferedWriter = new BufferedWriter(writer);
          bufferedWriter.write(strContent);
      } catch (Exception e) {
          e.printStackTrace();
      } finally{
          try{
              if(bufferedWriter != null) {
            	  bufferedWriter.close();
            	  System.out.println("Successfully write "
            	  		+ "string content to file.");
              }
          } catch(Exception ex){
        	  ex.printStackTrace();
          }
      }
  }
}

Output:

Stored data in temporary file.
Successfully write string content to file.

Download this example.