Create Temporary Directories in Java

The temporary directory is most commonly used in java, to store the files, When we create temporary directories, we can delegate to the operating system where to put them or specify ourselves where we want to place them.

There many ways to create Create Temporary Directories in Java.

1). Using core java

JDK 7 uses the new Files.createTempDirectory class to create the temporary directory.

a). Temporary File/Directory in the OS's default location

import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.io.File; public class CreateTempFile1 { public static void main(String[] args) throws Exception { final File temp; temp = File.createTempFile("temp", Long.toString(System.nanoTime())); if (! (temp.delete())) { throw new Exception("Could not delete temp file: " + temp.getAbsolutePath()); } if (! (temp.mkdir())) { throw new Exception("Could not create temp : " + temp.getAbsolutePath()); } System.out.println("the temp file is: " + temp); } } output: the temp file is: /tmp/temp86109225733384211687384313994002388

We can create temp files with suffix or prefix

Path temp = Files.createTempFile(null, ".log"); System.out.println("Temp file : " + temp); // Temp file : /tmp/86109225733384211687384313994002388.log

b). temporary File/Directory in a custom location with a custom prefix and suffix

// D:\tmp\log_13299365648984256372.txt Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp"); String customFilePrefix = "log_"; String customFileSuffix = ".txt"; Path tmpCustomLocationPrefixSuffix = Files.createTempFile(customBaseDir, customFilePrefix, customFileSuffix);

2). Using Google Guava library

The Google Guava library has a ton of helpful utilities. One of note here is the Files class. It has a bunch of useful methods including:

File myTempDir = Files.createTempDir();

3). Using Test framework

If you need a temporary directory for testing and you are using jUnit, @Rule together with TemporaryFolder solves your problem.

@Rule public TemporaryFolder folder = new TemporaryFolder();

In this article, we have seen Create Temporary Directories in Java.