我想将文件从一个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);
}
}
。
答案 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
答案 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
}