Copy thư mục trong Java

Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu cách copy một thư mục sử dụng Java code. Việc copy một thư mục phức tạp hơn copy một tập tin vì trong thư mục còn chứa các tập tin và thư mục con trong đó, mỗi thư mục con lại có các tập tin và thư mục con và v.v. 

Copy thư mục sử dụng java.nio

Java NIO được giới thiệu từ Java 1.4 và sau đó Java NIO2 được giới thiệu trong Java 7 cung cấp nhiều tính năng hơn như hỗ trợ xử ý symbolic links, tính năng truy cập và xử lý trên các tập tin. Ngoài ra nó còn cung cấp Path, PathsFiles class cho phép chúng ta thao tác dễ dàng và ngắn gọn hơn.

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();
          }
      });
}

Trong đoạn mã trên, chúng ta sử dụng Files.walk() để duyệt qua cây thư mục của thư mục cần copy. Với mỗi thư mục hoặc tập tin được tìm thấy sử dụng Files.copy() để copy sang thư mục mới tương ứng.

Copy thư mục sử dụng java.io

Java NIO có lẽ là cách ngắn gọn và tiện lợi nhất để copy thư mục ở thời điểm hiện tại. Tuy nhiên, nếu bạn đang sử dụng Java phiên bản thấp hơn 7, chúng ta có thể sử dụng Java IO.

Sử dụng Java IO chúng ta sẽ phải triển khai mã nguồn nhiều hơn với 3 method: 

  • copyDirectory – là method chính dùng để copy thư mục.
  • copyDirectoryCompatibityMode – hỗ trợ cho copyDirectory, dùng để xác định xem tài nguyên hiện tại là thư mục hay là tập tin để gọi hàm copyFile hoặc copyDirectory tương ứng.
  • copyFile dùng để sao chép các tập tin.
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));
    }
}

// --------------------------------------------------------------------------------------------------------
public static void copyDirectoryCompatibityMode(File source, File destination) throws IOException {
    if (source.isDirectory()) {
        copyDirectory(source, destination);
    } else {
        copyFile(source, destination);
    }
}
// ---------------------------------------------------------------------------------------------------------
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);
        }
    }
}

Copy thư mục sử dụng Apache commons IO

Apache Commons IO có rất nhiều tính năng hữu ích như các lớp tiện ích để triển khai các thao tác IO. Trong bài viết này chúng ta sẽ sử dụng FileUtils để sao chép thư mục.

Trước thêm chúng ta cần thêm commons-io dependency:

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

Và việc copy thư mục với commons-io rất đơn giản với method được cung cấp sẵn

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

Nguồn

https://www.baeldung.com/java-copy-directory

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x