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

时间:2016-01-22 15:38:38

标签: java path filesystems jvm-languages

我想将文件从一个java.nio.file.FileSystem复制到另一个com.google.common.jimfs.Jimfs。例如,从默认文件系统到// 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); } }

2 个答案:

答案 0 :(得分:3)

我为这个用例编写了一些实用程序类。该库是开源的,也许您觉得它很有用:

CopyFileVisitor.copy(srcPath, targetPath);  

的Maven:

<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

答案 1 :(得分:0)

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

// 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))
  }
}

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

partial void OnCreated()
{
    this.CommandTimeout = 3600; //value in seconds
}