1

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?

Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66
  • 1
    Ah...you should either move the directory in the postVisitDirectory or skip the visitFile. The FileVisitor will run the previsit /foo then /foo/file1.txt then /foo/file2.txt then the postvisit for /foo. When it runs the previsit /foo you are moving /foo (and everything under it). Then when it runs /foo/file1.txt you have already moved /foo/file1.txt (because you moved /foo). – Pace May 03 '13 at 14:20

0 Answers0