Java Create Temp File or Directory

In Java, creating a temporary file can be required in many scenarios for example unit testing, batch operations, file uploads or large request processings where the result of intermediate operations must be saved to refer to later.

This Java tutorial discusses a few simple ways to create temp files or directories.

Path tempFile = Files.createTempFile("test-data-", ".txt"); //NIO
//tempFile.toFile().deleteOnExit();

File tempFile = File.createTempFile("test-data-", ".txt") //Legacy
//tempFile.deleteOnExit();

Path tempDirectory = Files.createTempDirectory("temp-dir"); //Create Temp Directory
//Clean up with shutdown hook

If we intend to create temp files/directories in unit testing, we better use the TemporaryFolder (JUnit 4) or @TempDir (JUnit 5). They allow the creation of files and directories that are guaranteed to be deleted when the test method finishes (whether test passes or fails).

1. Default Location of Temp Files or Directories

It is important to know that if the target location is not specified, the temp file/directory is created in the default temp directory specified by the system property java.io.tmpdir.

  • Windows – %USER%/AppData/Local/Temp/
  • Linux or macOS – /tmp/

2. Create Temp Files

2.1. Using Files.createTempFile() [Java NIO]

The java.nio.file.Files.createTempFile() method is an overloaded method. Both methods will create the file only if there is no file with the same name and location that exist before the method is called.

Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)
Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)
  • dir – directory in which the file is to be created. If null, the default location will be used as specified in the previous section.
  • prefix – is used in generating the file’s name. It must be at least three characters long.
  • suffix – is used in generating the file’s name (generally extension). If null, ".tmp" will be used.

In the given example, the created temporary file will be deleted when the program exits.

FileAttribute<?>[] attributes = {
    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r--r--"))
};

Path tempFile = Files.createTempFile(Files.createTempDirectory("temp-dir"), "testData-", ".txt", attributes);

System.out.println(tempFile.toAbsolutePath().toString());

Program Output:

<Default temp path>\temp-dir10165603645741470295\testData-17461647418384794020.txt

If we want to delete the temporary file automatically, open the file with DELETE_ON_CLOSE option so that the file is deleted when the appropriate close() method is invoked after we have processed the file, such as writing to the temporary file.

Path tempFile;

try {

  tempFile = Files.createTempFile("testData-", ".txt");

  try (var outputStream = Files.newOutputStream(tempFile, StandardOpenOption.DELETE_ON_CLOSE)) {

    // Write data to the file or perform operations...
  } 
} catch (IOException e) {
  //...
}

Alternatively, a shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the file automatically.

try {
   tempFile = Files.createTempFile("testData-", ".txt");
   tempFile.toFile().deleteOnExit();
}

2.1. Using File.createTempFile() [Legacy]

This java.io.File.createTempFile() works similarly to Files.createTempFile(), as seen in the previous example. It creates a new empty temporary file in the specified directory using the given prefix and suffix strings to generate its name.

The only difference between both approaches is that it uses the legacy Java classes.

File createTempFile(String prefix, String suffix) throws IOException
File createTempFile(String prefix, String suffix, File directory) throws IOException

Let us see an example.

File tempFile;

try {
   tempFile = File.createTempFile("testData-", ".txt");
   System.out.println("Temp file created : " + tempFile.getAbsolutePath());
} 
catch (IOException e) {
  //...
}

If we want to delete the temp file automatically when the virtual machine terminates, use the deleteOnExit() method.

File tempFile;

try {
   tempFile = File.createTempFile("testData-", ".txt");
   tempFile.deleteOnExit();   //deletes file when the virtual machine terminate
   //...
} 

3. Creating Temp Directory

Similar to temporary files, we can use both previously discussed classes for creating the temporary directories as well:

static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) throws IOException
static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException

In simple usecases, we create a directory by specifying the prefix for the directory name:

Path tempDir = Files.createTempDirectory("tempDirPrefix-");

Alternatively, we can also pass the location of the temp directory to be created.

Path tmpdir = Files.createTempDirectory(Paths.get("/temp/data/"), "tempDirPrefix-");

Note that Java doesn’t automatically delete the directory when the JVM exits. If we want the created temporary directory to be deleted automatically when the JVM exits, we’ll need to register a shutdown hook to take care of the cleanup.

In the following example, Files.walk recursively traverse the directory and its contents in reverse order and delete each file and subdirectory.

try {
  // Create a temporary directory
  Path tempDirectory = Files.createTempDirectory("temp-dir");

  // Register a shutdown hook to delete the directory when the JVM exits
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    try {
      Files.walk(tempDirectory)
          .sorted((p1, p2) -> -p1.compareTo(p2))
          .forEach(path -> {
              try {
                  Files.delete(path);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          });
    } catch (IOException e) {
      e.printStackTrace();
    }
  }));

  // Do some work with the temporary directory...

} catch (IOException e) {
  e.printStackTrace();
}

Remember that using a shutdown hook can be useful, but it might not cover all potential scenarios (e.g., forceful termination of the JVM).

4. Conclusion

In Java, using the java.nio.file.Files class is the best approach for creating a temporary file or temporary directory. Using any other 3rd party library may not bring any additional benefit.

It is important to clean up the temporary files and directories if they have been created to store intermediate results only. This will help in keeping the OS size in check.

Happy Learning !!

Sourceocde on Github

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode