1. Creating temporary files: Files.createTempFile
Temporary files are used to store intermediate data, cache, or any results that aren’t meant for long-term storage. As a rule, they live exactly as long as the program runs or until the data is no longer needed.
Most often, temporary files are used when downloading large documents (we first download them to a temporary folder and then move them to the desired location), when caching information that can be recomputed or fetched again, for storing intermediate results when processing large data sets, and also for data exchange between parts of a program or threads. Another common scenario is tests: it’s more convenient to write to temp files than to clutter working directories.
You can think of temporary files as drafts for your program. They aren’t for the public, but without them you can’t always get the job done.
In Java, creating such a file is very easy—literally a one-liner. Use the method Files.createTempFile.
Simple example
import java.nio.file.*;
public class TempFileExample {
public static void main(String[] args) throws Exception {
// Create a temporary file with prefix "myapp_" and suffix ".tmp"
Path tempFile = Files.createTempFile("myapp_", ".tmp");
System.out.println("Temporary file created: " + tempFile);
// You can write data into it
Files.writeString(tempFile, "This is temporary data");
// Read it back
String data = Files.readString(tempFile);
System.out.println("Contents: " + data);
}
}
What’s happening?
- The file is created in the system temporary directory (usually "/tmp" on Linux or "C:\\Users\\<name>\\AppData\\Local\\Temp" on Windows).
- The file name will be something like "myapp_1234567890.tmp".
- The file already exists on disk; you can work with it like a regular file.
Method arguments
- The first argument is the prefix of the file name (for example, "myapp_").
- The second argument is the suffix (for example, ".tmp"). If you don’t specify it, ".tmp" will be used.
- If both arguments are null, defaults are used for the generated name.
Where is the file saved?
By default, the file is saved in the system temporary directory. But you can specify your own:
Path tempDir = Paths.get("my_temp_folder");
Files.createDirectories(tempDir); // Create it if it doesn't exist
Path tempFile = Files.createTempFile(tempDir, "prefix_", ".txt");
2. Creating temporary directories: Files.createTempDirectory
Sometimes you need not just a temporary file but an entire temporary folder—for example, to extract an archive or to temporarily store many files.
Example
import java.nio.file.*;
public class TempDirExample {
public static void main(String[] args) throws Exception {
// Create a temporary directory with the prefix "work_"
Path tempDir = Files.createTempDirectory("work_");
System.out.println("Temporary folder: " + tempDir);
// You can create files in it
Path fileInTempDir = Files.createTempFile(tempDir, "file_", ".dat");
System.out.println("Temporary file inside: " + fileInTempDir);
}
}
Notes:
- The folder name will look like "work_1234567890".
- By default, it’s created in the system temp directory, but you can specify any other directory.
Specifying the directory
Path baseDir = Paths.get("my_temp_work");
Files.createDirectories(baseDir);
Path tempDir = Files.createTempDirectory(baseDir, "session_");
3. Deleting temporary files and directories
Here lies one of Java’s main “gotchas”: temporary files and folders are not deleted automatically! If you don’t clean them up, they will remain on disk and can stick around for years (or until the system cleans them up).
How to delete temporary files?
- Manually: after you’re done with the file, call Files.delete(...) or Files.deleteIfExists(...).
- At program shutdown: you can use the old File.deleteOnExit() method, but only for File objects, not Path.
Example: deleting a temporary file
import java.nio.file.*;
public class TempFileDeleteExample {
public static void main(String[] args) throws Exception {
Path tempFile = Files.createTempFile("demo_", ".tmp");
System.out.println("Created: " + tempFile);
// ... work with the file
// Delete the file
Files.deleteIfExists(tempFile);
System.out.println("Deleted: " + tempFile);
}
}
Using deleteOnExit()
import java.io.File;
public class DeleteOnExitDemo {
public static void main(String[] args) throws Exception {
File tempFile = File.createTempFile("legacy_", ".tmp");
System.out.println("Created: " + tempFile);
// Mark the file for deletion when the JVM exits
tempFile.deleteOnExit();
}
}
Warning!
The deleteOnExit() method works only with File, not with Path. If you use the modern API (Path and Files), delete manually.
Deleting temporary directories
You can delete a temporary folder only if it’s empty:
Files.delete(tempDir); // will throw an exception if anything remains inside
If there are files in the folder, delete them first, then the folder. Usually, a small recursive method is written for this.
4. Practical recommendations
Where to store temporary files?
System temporary directory:
Use it by default if you have no special requirements. You can get the path like this:
String tempDir = System.getProperty("java.io.tmpdir");
System.out.println("System temp folder: " + tempDir);
Custom folder:
If security or organization are important, create a separate folder (for example, inside the application directory).
Security
- Do not store temporary files in publicly accessible folders—especially if they might contain something sensitive.
- Clean up temporary files after use—otherwise they can accumulate and take up space.
Cleanup on errors
If an error occurs during program execution, don’t forget to delete temporary files. It’s convenient to use try-finally blocks for this:
Path tempFile = Files.createTempFile("task_", ".tmp");
try {
// use the file
} finally {
Files.deleteIfExists(tempFile);
}
Temporary files and testing
Tests often use temporary files and folders to isolate data. After a test, be sure to delete everything created!
5. Example: a temporary working directory for data processing
Suppose you’re writing a program that processes an archive and temporarily unpacks files. It’s convenient to create a temporary folder for this and delete it after the work is complete.
import java.nio.file.*;
import java.io.IOException;
public class TempWorkDirExample {
public static void main(String[] args) throws IOException {
// Create a temporary directory
Path tempWorkDir = Files.createTempDirectory("unzip_");
System.out.println("Temporary working folder: " + tempWorkDir);
try {
// Archive extraction could be here
Path tempFile = Files.createTempFile(tempWorkDir, "file_", ".txt");
Files.writeString(tempFile, "Temporary data for processing");
// ... work with files
} finally {
// Delete all files in the folder and the folder itself
Files.walk(tempWorkDir)
.sorted((a, b) -> b.compareTo(a)) // files first, then folders
.forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException ex) {
System.err.println("Failed to delete " + path + ": " + ex.getMessage());
}
});
System.out.println("Temporary folder and files deleted.");
}
}
}
Note:
Delete all files first, then the folder itself. Sorting is required to avoid trying to delete a folder before its contents have been deleted.
6. Common mistakes when working with temporary files
Mistake #1: you forgot to delete a temporary file or folder. The most common issue is that temp files stay on disk, accumulate, and over time lead to system clutter. This is especially critical for server applications and long-running processes.
Mistake #2: using deleteOnExit() for Path. The deleteOnExit() method works only with the File class, not with Path. If you use the modern API, you’ll have to delete manually.
Mistake #3: trying to delete a non-empty folder with Files.delete. The Files.delete() method deletes only empty directories. If anything remains inside, an exception will be thrown. To delete non-empty directories, walk recursively and delete all files.
Mistake #4: creating temporary files in the project’s working directory. This can lead to accidental deletion of important files or to confusion. It’s better to use the system temp folder or a dedicated temp folder for the application.
Mistake #5: not handling exceptions when deleting temporary files. If a file is already deleted or locked, an attempt to delete it may throw an exception. Use Files.deleteIfExists() and handle errors.
GO TO FULL VERSION