Java:使用 nio Files.copy 移动目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15137849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Using nio Files.copy to Move Directory
提问by Adam_G
I am new to the nio class, and am having trouble moving a directory of files to a newly created directory.
我是 nio 类的新手,无法将文件目录移动到新创建的目录。
I first create 2 directories with:
我首先创建 2 个目录:
File sourceDir = new File(sourceDirStr); //this directory already exists
File destDir = new File(destDirectoryStr); //this is a new directory
I then try to copy the existing files into the new directory, using:
然后我尝试使用以下方法将现有文件复制到新目录中:
Path destPath = destDir.toPath();
for (int i = 0; i < sourceSize; i++) {
Path sourcePath = sourceDir.listFiles()[i].toPath();
Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
This throws the following error:
这会引发以下错误:
Exception in thread "main" java.nio.file.FileSystemException: destDir/Experiment.log: Not a directory
I know that destDir/Experiment.log
is not an existing directory; it should be a new file as a result of the Files.copy
operation. Could someone point out where my operation is going wrong? Thanks!
我知道这destDir/Experiment.log
不是现有目录;作为Files.copy
操作的结果,它应该是一个新文件。有人能指出我的操作哪里出了问题吗?谢谢!
回答by AaronHolland
You need to use walkFileTree to copy directories. If you use Files.copy on a directory only an empty directory will be created.
您需要使用 walkFileTree 来复制目录。如果您在目录上使用 Files.copy,则只会创建一个空目录。
Following code taken/adapted from http://codingjunkie.net/java-7-copy-move/
以下代码取自/改编自http://codingjunkie.net/java-7-copy-move/
File src = new File("c:\temp\srctest");
File dest = new File("c:\temp\desttest");
Path srcPath = src.toPath();
Path destPath = dest.toPath();
Files.walkFileTree(srcPath, new CopyDirVisitor(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING));
public static class CopyDirVisitor extends SimpleFileVisitor<Path>
{
private final Path fromPath;
private final Path toPath;
private final CopyOption copyOption;
public CopyDirVisitor(Path fromPath, Path toPath, CopyOption copyOption)
{
this.fromPath = fromPath;
this.toPath = toPath;
this.copyOption = copyOption;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
{
Path targetPath = toPath.resolve(fromPath.relativize(dir));
if( !Files.exists(targetPath) )
{
Files.createDirectory(targetPath);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
Files.copy(file, toPath.resolve(fromPath.relativize(file)), copyOption);
return FileVisitResult.CONTINUE;
}
}
回答by RudolphEst
Simply make the destination directory if it doesn't exist.
如果目标目录不存在,只需制作目标目录。
File sourceDir = new File(source); //this directory already exists
File destDir = new File(dest); //this is a new directory
destDir.mkdirs(); // make sure that the dest directory exists
Path destPath = destDir.toPath();
for (File sourceFile : sourceDir.listFiles()) {
Path sourcePath = sourceFile.toPath();
Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
Note that sourceDir.listFiles()
will also return directories, which you will either want t recurse into, or ignore...
请注意,sourceDir.listFiles()
这也将返回目录,您要么不想递归,要么忽略...
回答by user207421
for (int i = 0; i < sourceSize; i++) {
Path sourcePath = sourceDir.listFiles()[i].toPath();
Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
This is very strange code. You have already got a file count from somewhere, in sourceSize
, yet you are calling listFiles()
for every iteration. I would have expected something more like this:
这是非常奇怪的代码。您已经从某个地方获得了文件计数 in sourceSize
,但您listFiles()
每次迭代都在调用。我本来期望更像这样的:
for (File file : sourceDir.listFiles()) {
Path sourcePath = file.toPath();
Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName()));
}
回答by Downhillski
This is my solution for recursively moving a directory from source to target. It works like a charm.
这是我将目录从源递归移动到目标的解决方案。它就像一个魅力。
public static void move(Path source, Path target) throws IOException {
class FileMover extends SimpleFileVisitor<Path> {
private Path source;
private Path target;
private FileMover(Path source, Path target) {
this.source = source;
this.target = target;
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.move(file, target.resolve(source.relativize(file)),
StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
Path newDir = target.resolve(source.relativize(dir));
try {
Files.copy(dir, newDir,
StandardCopyOption.COPY_ATTRIBUTES,
StandardCopyOption.REPLACE_EXISTING);
} catch (DirectoryNotEmptyException e) {
// ignore and skip
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
Path newDir = target.resolve(source.relativize(dir));
FileTime time = Files.getLastModifiedTime(dir);
Files.setLastModifiedTime(newDir, time);
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
}
FileMover fm = new FileMover(source, target);
EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Files.walkFileTree(source, opts, Integer.MAX_VALUE, fm);
}