移动文件时发生java异常
我假设这与我对FileVisitor
如何工作和解析目录的有限知识有关。我要做的是将一个目录的内容移动到另一个目录中。我通过如下方式实现FileVisitor<Path>
来实现这一点:
public class Mover implements FileVisitor<Path> {
private Path target;
private Path source;
public Mover(Path source, Path target) {
this.target = target;
this.source = source;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path targetDir = target.resolve(source.relativize(dir));
try {
Files.move(dir, targetDir);
} catch (FileAlreadyExistsException e) {
if(!Files.isDirectory(targetDir)) {
System.out.println("Throwing e!");
throw e;
}
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try {
Files.move(file, target.resolve(source.relativize(file)));
} catch (NoSuchFileException e) {
//TODO: Figure out why this exception is raised!
System.out.println("NoSuchFileException");
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
}
反过来,我使用我的类Mover
,如下所示:
Files.walkFileTree(from, new Mover(from, to));
我不喜欢在调用walkFileTree
时添加from
两次,但目前我的问题主要是代码中TODO
下的行(不过我非常感谢您对如何解决该问题的任何意见)。我不明白为什么会提出这个例外。我猜这是因为文件已经被移动了。如果是这样的话,我该如何阻止我的代码再次尝试移动它,我现在这样做或多或少是正确的吗
# 1 楼答案
下面是一个函数,它将以编程方式移动文件
在清单中设置正确的权限
要删除文件,请使用
抄袭