1. Overview
1.概述
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.
在这个简短的教程中,我们将学习如何使用不同的API和方法在Java中创建临时目录。本教程中的所有示例都将使用普通的Java 7+、Guava和Apache Commons IO进行。
2. Delegate to the Operating System
2.委托给操作系统
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.
用于创建临时目录的最流行的方法之一是将目的地委托给底层操作系统。位置由java.io.tmpdir属性给出,每个操作系统都有自己的结构和清理程序。
In plain Java, we create a directory by specifying the prefix we want the directory to take:
在普通的Java中,我们通过指定我们想要的目录的前缀来创建一个目录。
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:
使用Guava,过程类似,但我们不能指定我们要如何给我们的目录加前缀。
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:
Apache Commons IO并没有提供创建临时目录的方法。它提供了一个包装器来获取操作系统的临时目录,然后,剩下的就由我们来做。
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.
为了避免与现有目录的名称冲突,我们使用UUID.randomUUID()来创建一个随机名称的目录。
3. Specifying the Location
3.指定地点
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:
有时我们需要指定在哪里创建临时目录。一个很好的例子是在Maven构建过程中。由于我们已经有了一个 “临时 “构建target目录,我们可以利用该目录来放置我们构建可能需要的临时目录。
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.
Guava和Apache Commons IO都缺乏在特定位置创建临时目录的方法。
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.
值得注意的是,target目录可以是不同的,取决于构建配置。有一种方法可以使其不受影响,就是将目标目录的位置传递给运行测试的JVM。
As the operating system isn’t taking care of the cleanup, we can make use of File.deleteOnExit():
由于操作系统不负责清理工作,我们可以利用File.deleteOnExit()。
tmpdir.toFile().deleteOnExit();
This way, the file is deleted once the JVM terminates, but only if the termination is graceful.
这样,一旦JVM终止,该文件就会被删除,但前提是终止是优雅的。
4. Using Different File Attributes
4.使用不同的文件属性
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.
正如预期的那样,Guava和Apache Commons IO没有提供在创建临时目录时指定属性的方法。
It’s also worth noting that the previous example assumes we are under a Posix Compliant Filesystem such as Unix or macOS.
还值得注意的是,前面的例子假设我们是在一个符合Posix标准的文件系统下,如Unix或macOS。
More information about file attributes can be found in our Guide to NIO2 File Attribute APIs.
关于文件属性的更多信息可以在我们的NIO2文件属性API指南中找到。
5. Conclusion
5.总结
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.
在这个简短的教程中,我们探讨了如何在纯Java 7+、Guava和Apache Commons IO中创建临时目录。我们看到,纯Java是创建临时目录的最灵活的方式,因为它提供了更多的可能性,同时将冗长的言语保持在最低限度。
As usual, all the source code for this tutorial is available over on GitHub.
像往常一样,本教程的所有源代码都可以在GitHub上找到。