A temporary file is used to store data for a short period and is commonly used for caching, intermediate processing, and temporary data storage. Java provides built-in methods to safely create temporary files, typically with a .tmp extension or a custom extension such as .txt.
- Temporary files are created using the File.createTempFile() method.
- deleteOnExit() removes the file automatically when the JVM terminates.
- getAbsolutePath() returns the complete location of the created file.
Syntax
Importing File Classes
import java.io.File;
import java.io.IOException;
Creating a File Object
File file = new File("Directory_Path");
Creating a Temporary File
File tempFile = File.createTempFile("prefix",.txt",directory);
Methods For Temporary File Creation
The following methods can be used to create temporary files in Java.
1: Using File.createTempFile()
The createTempFile() method creates a uniquely named temporary file in a specified directory.
Syntax
File.createTempFile(String prefix,String suffix, File directory)
import java.io.File;
import java.io.IOException;
public class TempFileExample1 {
public static void main(String[] args)
throws IOException {
// Directory path
File directory = new File("D:/Temp");
// Creating temporary file
File tempFile = File.createTempFile(
"sample_", ".txt", directory);
System.out.println(
"Temporary File Created:");
System.out.println(
tempFile.getAbsolutePath());
// Delete file
tempFile.delete();
System.out.println(
"Temporary File Deleted");
}
}
Output: Temporary File Created:
D:\Temp\sample_873241.txt
Temporary File Deleted
Explanation:
- A directory object is created.
- createTempFile() generates a unique file name.
- getAbsolutePath() prints the complete file location.
- delete() removes the file immediately.
2: Using deleteOnExit()
Instead of deleting the file immediately, Java can delete it automatically when the JVM exits.
import java.io.File;
import java.io.IOException;
public class TempFileExample2 {
public static void main(String[] args)
throws IOException {
// Create temporary file
File file = File.createTempFile(
"temp_", ".txt");
// Print file path
System.out.println(
"File Location:");
System.out.println(
file.getAbsolutePath());
// Delete after JVM exits
file.deleteOnExit();
System.out.println(
"File will be deleted on program exit.");
}
}
Output
File Location: /tmp/temp_13959981152995046380.txt File will be deleted on program exit.
Explanation:
- createTempFile() creates a temporary file in the default system location.
- getAbsolutePath() prints the complete file path.
- deleteOnExit() schedules the file for deletion when the JVM terminates.