Files#walkFileTreeは、ディレクトリ構造を再帰的に走査する。walkFileTreeメソッドの2つ目の引数にFileVisitorインターフェースの実装をセットする。
/** * 指定したディレクトリ配下をすべて削除します。 * * @param dir * @throws IOException */ public static void deleteAll(Path dir) throws IOException { Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { throw exc; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); }
/** * srcディレクトリ配下をdestディレクトリへコピーします。 * * @param src コピー元 * @param dest コピー先 * @throws IOException */ public static void copyAll(Path src, Path dest) throws IOException { Files.walkFileTree(src, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path targetFile = dest.resolve(src.relativize(file)); Path parentDir = targetFile.getParent(); Files.createDirectories(parentDir); Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } } ); }