Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

Temporary directories come in handy when we need to create a set of files that we can later discard. 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.

In this short tutorial, we'll learn how to create temporary directories in Java using different APIs and approaches. All the examples in this tutorial will be performed using plain Java 7+, Guava, and Apache Commons IO.

2. Delegate to the Operating System

One of the most popular approaches used to create temporary directories is to delegate the destination to the underlying operating system. The location is given by the java.io.tmpdir property, and every operating system has its own structure and cleanup routines.

In plain Java, we create a directory by specifying the prefix we want the directory to take:

String tmpdir = Files.createTempDirectory("tmpDirPrefix").toFile().getAbsolutePath();
String tmpDirsLocation = System.getProperty("java.io.tmpdir");
assertThat(tmpdir).startsWith(tmpDirsLocation);

Using Guava, the process is similar, but we can't specify how we want to prefix our directory:

String tmpdir = Files.createTempDir().getAbsolutePath();
String tmpDirsLocation = System.getProperty("java.io.tmpdir");
assertThat(tmpdir).startsWith(tmpDirsLocation);

Apache Commons IO doesn't provide a way to create temporary directories. It provides a wrapper to get the operating system temporary directory, and then, it's up to us to do the rest:

String tmpDirsLocation = System.getProperty("java.io.tmpdir");
Path path = Paths.get(FileUtils.getTempDirectory().getAbsolutePath(), UUID.randomUUID().toString());
String tmpdir = Files.createDirectories(path).toFile().getAbsolutePath();
assertThat(tmpdir).startsWith(tmpDirsLocation);

In order to avoid name clashes with existing directories, we use UUID.randomUUID() to create a directory with a random name.

3. Specifying the Location

Sometimes we need to specify where we want to create our temporary directory. A good example is during a Maven build. Since we already have a “temporary” build target directory, we can make use of that directory to place temporary directories our build might need:

Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
assertThat(tmpdir.toFile().getPath()).startsWith("target");

Both Guava and Apache Commons IO lack methods to create temporary directories at specific locations.

It's worth noting that the target directory can be different depending on the build configuration. One way to make it bullet-proof is to pass the target directory location to the JVM running the test.

As the operating system isn't taking care of the cleanup, we can make use of File.deleteOnExit():

tmpdir.toFile().deleteOnExit();

This way, the file is deleted once the JVM terminates, but only if the termination is graceful.

4. Using Different File Attributes

Like any other file or directory, it's possible to specify file attributes upon the creation of a temporary directory. So, if we want to create a temporary directory that can only be read by the user that creates it, we can specify the set of attributes that will accomplish that:

FileAttribute<Set> attrs = PosixFilePermissions.asFileAttribute(
  PosixFilePermissions.fromString("r--------"));
Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();

As expected, Guava and Apache Commons IO do not provide a way to specify the attributes when creating temporary directories.

It's also worth noting that the previous example assumes we are under a Posix Compliant Filesystem such as Unix or macOS.

More information about file attributes can be found in our Guide to NIO2 File Attribute APIs.

5. Conclusion

In this short tutorial, we explored how to create temporary directories in plain Java 7+, Guava, and Apache Commons IO. We saw that plain Java is the most flexible way to create temporary directories as it offers a wider range of possibilities while keeping the verbosity to a minimum.

As usual, all the source code for this tutorial is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
guest
0 Comments
Inline Feedbacks
View all comments