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.
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.
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.
B. Delete the file immediately:
We can delete a temporary file with the use delete() method.
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.