How to Delete Temporary File in Java?
Last Updated :
05 Aug, 2021
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.
Java
import java.io.File;
import java.io.IOException;
public class tempFile {
public static void main(String args[])
throws IOException
{
String prefix = "TempFile" ;
String suffix = ".txt" ;
File directoryPath = new File(
"/home/krishna/Desktop/java/junior/" );
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
import java.io.File;
import java.io.IOException;
public class tempFile {
public static void main(String[] args)
{
File temp;
try {
temp = File.createTempFile( "TempFile" , ".txt" );
temp.deleteOnExit();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
B. Delete the file immediately:
We can delete a temporary file with the use delete() method.
Java
import java.io.File;
import java.io.IOException;
public class tempFile {
public static void main(String[] args)
{
File temp;
try {
temp
= File.createTempFile( "myTempFile" , ".txt" );
temp.delete();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...