Java: Using nio Files.copy to Move Directory

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...


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);
}

You need to use walkFileTree to copy directories. If you use Files.copy on a directory only an empty directory will be created.

Following code taken/adapted from 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;
    }
}

Tags:

Java

File

Nio