delete temporary file java program

Example:

package com.w3schools;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
 
public class TempFileDelete {
  public static void main(String args[]){
      File tempFile = null;
      BufferedWriter writer = null;
      try {
          tempFile = File.createTempFile("TempFile", ".tmp");
          writer = new BufferedWriter(new FileWriter(tempFile));
          writer.write("Test Content");
      } catch (Exception e) {
          e.printStackTrace();
      }
      System.out.println("Stored data in temporary file.");
      tempFile.deleteOnExit();
      System.out.println("Temporary file deleted successfully.");
  }
}

Output:

Stored data in temporary file.
Temporary file deleted successfully.

Download this example.