I'm assuming that this has to do with my limited knowledge of how the FileVisitor
works and parses the directories. What I'm trying to do is to move the contents of a directory into another directory. I'm doing this by implementing FileVisitor<Path>
like this:
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;
}
}
In turn I use my class Mover
like this:
Files.walkFileTree(from, new Mover(from, to));
I don't like that I add from
twice when calling walkFileTree
, but currently my problem is mainly with the line under the TODO
in my code (however I would very much appreciate any comments on how to solve that to). I don't understand why that exception is raised. I'm guessing that it is because the file is already moved. If that is the case how do I go about to stop my code from trying to move it again, is the way I'm doing it now more or less correct?