Java – Create a File – Java – 创建一个文件

最后修改: 2014年 6月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to learn how to create a new File in Java – first using the Files and Path classes from NIO, then the Java File and FileOutputStream classes, Google Guava, and finally the Apache Commons IO library.

在这个快速教程中,我们将学习如何在Java中创建一个新的文件–首先使用NIO的FilesPath类,然后是Java FileFileOutputStream类,Google Guava,最后是Apache Commons IO库。

This article is part of the “Java – Back to Basic” series here on Baeldung.

本文是Baeldung网站上“Java – Back to Basic “系列的一部分。

2. Setup

2.设置

In the examples, we’ll define a constant for the file name:

在例子中,我们将为文件名定义一个常量。

private final String FILE_NAME = "src/test/resources/fileToCreate.txt";

And we’ll also add a clean-up step to make sure that the file doesn’t already exist before each test, and to delete it after each test runs:

我们还将添加一个清理步骤,以确保在每次测试前文件不已经存在,并在每次测试运行后删除它。

@AfterEach
@BeforeEach
public void cleanUpFiles() {
    File targetFile = new File(FILE_NAME);
    targetFile.delete();
}

3. Using NIO Files.createFile()

3.使用NIO Files.createFile()

Let’s start by using the Files.createFile() method from the Java NIO package:

让我们从使用Java NIO包中的Files.createFile()方法开始。

@Test
public void givenUsingNio_whenCreatingFile_thenCorrect() throws IOException {
    Path newFilePath = Paths.get(FILE_NAME);
    Files.createFile(newFilePath);
}

As you can see the code is still very simple; we’re now using the new Path interface instead of the old File.

正如你所看到的,代码仍然非常简单;我们现在使用新的Path接口而不是旧的File

One thing to note here is that the new API makes good use of exceptions. If the file already exists, we no longer have to check a return code. Instead, we’ll get a FileAlreadyExistsException:

这里需要注意的一点是,新的API很好地利用了异常情况。如果文件已经存在,我们不再需要检查一个返回代码。相反,我们会得到一个FileAlreadyExistsException

java.nio.file.FileAlreadyExistsException: <code class="language-java">src/test/resources/fileToCreate.txt at sun.n.f.WindowsException.translateToIOException(WindowsException.java:81)

4. Using File.createNewFile()

4.使用File.createNewFile()

Let’s now look at how we can do the same using the java.io.File class:

现在让我们看看我们如何使用java.io.File类来做同样的事情

@Test
public void givenUsingFile_whenCreatingFile_thenCorrect() throws IOException {
    File newFile = new File(FILE_NAME);
    boolean success = newFile.createNewFile();
    assertTrue(success);
}

Note that the file must not exist for this operation to succeed. If the file does exist, then the createNewFile() operation will return false.

请注意,该文件必须不存在,该操作才能成功。如果文件确实存在,那么createNewFile()操作将返回false。

5. Using FileOutputStream

5.使用FileOutputStream

Another way to create a new file is to use the java.io.FileOutputStream:

另一种创建新文件的方法是使用java.io.FileOutputStream

@Test
public void givenUsingFileOutputStream_whenCreatingFile_thenCorrect() throws IOException {
    try(FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)){
    }
}

In this case, a new file is created when we instantiate the FileOutputStream object. If a file with a given name already exists, it will be overwritten. If, however, the existing file is a directory or a new file cannot be created for any reason, then we’ll get a FileNotFoundException.

在这种情况下,当我们实例化FileOutputStream对象时,会创建一个新文件。如果一个具有给定名称的文件已经存在,它将被覆盖。然而,如果现有的文件是一个目录,或者由于任何原因不能创建一个新的文件,那么我们将得到一个FileNotFoundException

Additionally, note we used a try-with-resources statement – to be sure that a stream is properly closed.

此外,注意我们使用了一个try-with-resources语句–以确保一个流被正确关闭。

6. Using Guava

6.使用番石榴

The Guava solution for creating a new file is a quick one-liner as well:

Guava创建新文件的方案也是一个快速的单行程序。

@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
    com.google.common.io.Files.touch(new File(FILE_NAME));
}

7. Using Apache Commons IO

7.使用Apache Commons IO

The Apache Commons library provides the FileUtils.touch() method which implements the same behavior as the “touch” utility in Linux.

Apache Commons库提供了FileUtils.touch()方法,实现了与Linux中”touch“工具相同的行为。

Therefore it creates a new empty file or even a file and the full path to it in a file system:

因此,它在文件系统中创建一个新的空文件,甚至是一个文件和它的完整路径。

@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
    FileUtils.touch(new File(FILE_NAME));
}

Note that this behaves slightly differently than the previous examples: if the file already exists, the operation doesn’t fail, it simply doesn’t do anything.

注意,这与前面的例子略有不同:如果文件已经存在,操作不会失败,只是不做任何事情。

And there we have it – 4 quick ways to create a new file in Java.

就这样,我们有了–在Java中创建新文件的4种快速方法。

8. Conclusion

8.结论

In this article, we looked at different solutions for creating a file in Java. We used classes that are part of the JDK and external libraries.

在这篇文章中,我们研究了在Java中创建文件的不同解决方案。我们使用了属于JDK的类和外部库。

The code for the examples is available over on GitHub.

例子的代码可在GitHub上找到。