How to Delete Temporary File in Java?
In java, we have a java.io package that provides various methods to perform various operations on files/directories.
Temporary files are those files that are created for some business logic or unit testing, and after using these files you have to make sure that these temporary files should be deleted. If you forget to delete these temporary files then this will take extra space while executing which is not efficient for your application.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
To Create Temporary File:- The file class which is present in the java.io package has createTempFile() method that will take two arguments i.e. name of the file(prefix) and extension (suffix) of the temp file. Provide an abstract path at which you need to create the temporary file.
Java
// Create temp fileimport java.io.File;import java.io.IOException;public class tempFile { public static void main(String args[]) throws IOException { // name of the file String prefix = "TempFile"; // extension of the file String suffix = ".txt"; // Creating a File object for directory File directoryPath = new File( "/home/krishna/Desktop/java/junior/"); // Creating a temp file File.createTempFile(prefix, suffix, directoryPath); System.out.println( "Temp file created at the specified path"); }} |
Output:
Temporary file has been created in the specified path

There are two ways you can delete an existing temporary file.
A. Delete when JVM exits:
You can use deleteOnExit() method to delete an existing file only when your application completes. If your code terminates abnormally then keep in mind that your temporary file has not been deleted yet and once you have requested for the delete operation then you can’t cancel afterwards.
Java
// Delete File when JVM Existsimport java.io.File;import java.io.IOException;public class tempFile { public static void main(String[] args) { File temp; try { // name of the file and extension temp = File.createTempFile("TempFile", ".txt"); // Delete when JVM exits temp.deleteOnExit(); } // If not found any temporary file catch (IOException e) { e.printStackTrace(); } }} |
B. Delete the file immediately:
We can delete a temporary file with the use delete() method.
Java
// Delete file using delete() methodimport java.io.File;import java.io.IOException;public class tempFile { public static void main(String[] args) { File temp; try { temp = File.createTempFile("myTempFile", ".txt"); // Perform other operations // Delete the file immediately temp.delete(); } // If not found the temporary file catch (IOException e) { e.printStackTrace(); } }} |


