在不同文件系统之间复制目录内容的干净方法?

A clean way to copy directory contents between different file systems?

我想将文件从一个 java.nio.file.FileSystem 复制到另一个。例如,从默认文件系统到 com.google.common.jimfs.Jimfs

下面我提出一个可以在Java中使用的解决方案如下:

// Java code
import com.google.common.jimfs.Jimfs;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class UsageExamples
{
  @Test
  public void UsageExample() throws IOException
  {
    Path dir  = Jimfs.newFileSystem().getPath("dirWithSomeContents");
    Path dest = Jimfs.newFileSystem().getPath("destDir");
    Files.createDirectory(dir);
    Files.createDirectory(dest);

    // Act
    new FileSystemsOperations().copyDirContentsRecursivelyToDirInDifferentFileSystem(dir, dest);
  }
}

我在 Groovy 中的解决方案(完整代码 on GitHub):

// Groovy code
import java.nio.file.Files
import java.nio.file.Path

class FileSystemsOperations
{

  void copyDirContentsRecursivelyToDirInDifferentFileSystem(Path srcDir, Path destDir)
  {
    assert Files.isDirectory(srcDir)
    assert Files.isDirectory(destDir)
    assert srcDir.fileSystem != destDir.fileSystem

    srcDir.eachFileRecurse {Path it ->
      copyPath(it, srcDir, destDir) }
  }


  private static Path copyPath(Path it, Path src, Path dest)
  {
    assert it != null
    assert Files.isDirectory(src)
    assert Files.isDirectory(dest)

    Path itInDest = mapToDestination(it, src, dest)

    assert !Files.exists(itInDest)

    if (Files.isDirectory(it))
    {
      Files.createDirectory(itInDest)

    } else if (Files.isRegularFile(it))
    {
      Files.copy(it, itInDest)

    } else
      assert false

    return itInDest
  }

  private static Path mapToDestination(Path path, Path srcDir, Path destDir)
  {
    return destDir.resolve(srcDir.relativize(path).toString().replace(srcDir.fileSystem.separator, destDir.fileSystem.separator))
  }
}

我已经为这个用例编写了一些实用程序 类。该库是开源的,也许您会发现它有用:

CopyFileVisitor.copy(srcPath, targetPath);  

专家:

<dependency>
    <groupId>org.softsmithy.lib</groupId>
    <artifactId>softsmithy-lib-core</artifactId>
    <version>0.5</version>
</dependency>

教程:http://www.softsmithy.org/softsmithy-lib/lib/0.5/docs/tutorial/nio-file/index.html

Javadoc:http://www.softsmithy.org/softsmithy-lib/lib/0.5/docs/api/softsmithy-lib-core/index.html

源代码:http://github.com/SoftSmithy/softsmithy-lib