5

I want to copy files from one java.nio.file.FileSystem to another one. For example, from default file system to com.google.common.jimfs.Jimfs.

Konrad Jamrozik
  • 3,254
  • 5
  • 29
  • 59

2 Answers2

3

I've written some utility classes for this use case. The library is Open Source, maybe you find it useful:

CopyFileVisitor.copy(srcPath, targetPath);  

Maven:

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

Tutorial: 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

Source code: http://github.com/SoftSmithy/softsmithy-lib

Puce
  • 37,247
  • 13
  • 80
  • 152
0

Below I present a solution that can be used in Java as follows:

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

My solution in Groovy (full code 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))
  }
}
Konrad Jamrozik
  • 3,254
  • 5
  • 29
  • 59