Copy a Directory in Java – 在Java中复制一个目录

最后修改: 2020年 8月 7日

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

1. Introduction

1.绪论

In this short tutorial, we’ll see how to copy a directory in Java, including all its files and subdirectories. This can be achieved by using core Java features or third-party libraries.

在这个简短的教程中,我们将看到如何在Java中复制一个目录,包括其所有文件和子目录。这可以通过使用Java核心功能或第三方库来实现。

2. Using the java.nio API

2.使用java.nio API

Java NIO has been available since Java 1.4. Java 7 introduced NIO 2 that brought a lot of useful features like better support for handling symbolic links, file attributes access. It also provided us with classes such as Path, Paths, and Files that made file system manipulation much easier.

Java NIO从Java 1.4开始就有了。Java 7引入了NIO 2,带来了很多有用的功能,如更好地支持处理符号链接、文件属性访问。它还为我们提供了诸如PathPathsFiles等类,使文件系统的操作更加容易。

Let’s demonstrate this approach:

让我们来演示一下这种方法。

public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) 
  throws IOException {
    Files.walk(Paths.get(sourceDirectoryLocation))
      .forEach(source -> {
          Path destination = Paths.get(destinationDirectoryLocation, source.toString()
            .substring(sourceDirectoryLocation.length()));
          try {
              Files.copy(source, destination);
          } catch (IOException e) {
              e.printStackTrace();
          }
      });
}

In this example, we walked the file tree rooted at the given source directory using Files.walk() and invoked Files.copy() for each file or directory we found in the source directory.

在这个例子中,我们使用Files.walk()走了根植于给定源目录的文件树,并为我们在源目录中发现的每个文件或目录调用了Files.copy()

3. Using the java.io API

3.使用java.io API

Java 7 was a turning point from the file system management perspective since it introduced a lot of new handy features.

从文件系统管理的角度来看,Java 7是一个转折点,因为它引入了很多新的方便的功能。

However, if we want to stay compatible with older Java versions, we can copy a directory using recursion and java.io.File features:

然而,如果我们想与旧的Java版本保持兼容,我们可以使用递归和java.io.File功能复制一个目录。

private static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException {
    if (!destinationDirectory.exists()) {
        destinationDirectory.mkdir();
    }
    for (String f : sourceDirectory.list()) {
        copyDirectoryCompatibityMode(new File(sourceDirectory, f), new File(destinationDirectory, f));
    }
}

In this case, we’ll create a directory in the destination directory for every directory in the source directory tree. Then we’ll invoke the copyDirectoryCompatibityMode() method:

在这种情况下,我们将在目标目录中为源目录树的每个目录创建一个目录。然后我们将调用copyDirectoryCompatibityMode()方法。

public static void copyDirectoryCompatibityMode(File source, File destination) throws IOException {
    if (source.isDirectory()) {
        copyDirectory(source, destination);
    } else {
        copyFile(source, destination);
    }
}

Also, let’s see how to copy a file using FileInputStream and FileOutputStream:

另外,让我们看看如何使用FileInputStreamFileOutputStream来复制一个文件。

private static void copyFile(File sourceFile, File destinationFile) 
  throws IOException {
    try (InputStream in = new FileInputStream(sourceFile); 
      OutputStream out = new FileOutputStream(destinationFile)) {
        byte[] buf = new byte[1024];
        int length;
        while ((length = in.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
    }
}

4. Using Apache Commons IO

4.使用Apache Commons IO

Apache Commons IO has a lot of useful features like utility classes, file filters, and file comparators. Here we’ll be using FileUtils that provide methods for easy file and directory manipulation, i.e., reading, moving, copying.

Apache Commons IO有很多有用的功能,如实用类、文件过滤器和文件比较器这里我们将使用FileUtils,它提供了方便文件和目录操作的方法,即读取、移动、复制。

Let’s add commons-io to our pom.xml file:

让我们把commons-io添加到我们的 pom.xml文件。

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Finally, let’s copy a directory using this approach:

最后,让我们用这种方法复制一个目录。

public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException {
    File sourceDirectory = new File(sourceDirectoryLocation);
    File destinationDirectory = new File(destinationDirectoryLocation);
    FileUtils.copyDirectory(sourceDirectory, destinationDirectory);
}

As shown in the previous example, Apache Commons IO makes it all much easier, since we only need to call FileUtils.copyDirectory() method.

正如前面的例子所示,Apache Commons IO使这一切变得更加容易,因为我们只需要调用FileUtils.copyDirectory()方法

5. Conclusion

5.总结

This article illustrated how to copy a directory in Java. Complete code samples are available over on GitHub.

这篇文章说明了如何在Java中复制一个目录。完整的代码样本可在GitHub上获得