In the Java API, when you use the File.createTempFile()
method, the temporary files created does not get automatically deleted when your program finishes or the file object goes out of scope. It is your responsibility to ensure the temporary file is deleted, either by explicitly calling the delete()
method or by setting the file to be deleted on exit using the deleteOnExit()
method.
Here’s an example of how to handle temporary files:
1. Creating and Deleting the File Explicitly:
import java.io.File;
import java.io.IOException;
public class TempFileExample {
public static void main(String[] args) {
try {
// Create a temporary file
File tempFile = File.createTempFile("example", ".tmp");
// Print the file path
System.out.println("Temporary file created: " + tempFile.getAbsolutePath());
// Delete the file explicitly when done
if (tempFile.delete()) {
System.out.println("Temporary file deleted.");
} else {
System.out.println("Failed to delete the temporary file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Using deleteOnExit()
:
If you want the temporary file to be deleted when the JVM exits, use the deleteOnExit()
method:
import java.io.File;
import java.io.IOException;
public class TempFileExample {
public static void main(String[] args) {
try {
// Create a temporary file
File tempFile = File.createTempFile("example", ".tmp");
// Print the file path
System.out.println("Temporary file created: " + tempFile.getAbsolutePath());
// Mark the file for deletion on JVM exit
tempFile.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Notes:
- Temporary File Location: The temporary file is created in the default system temporary directory, which is typically specified by the system property
java.io.tmpdir
. You can customize the location by passing a directory as the third parameter toFile.createTempFile()
. deleteOnExit()
Limitations:- It works only when the JVM exits normally (e.g.,
System.exit()
or completion of the main method). It won’t delete the file if the JVM crashes or is forcefully terminated. - Files marked for deletion with
deleteOnExit()
remain on disk until the JVM exits, which can cause memory issues if too many files are created in a long-running application.
- It works only when the JVM exits normally (e.g.,
To avoid leaving orphaned files, it’s best to delete them explicitly if possible. Check more Spring Boot Articles.