观看目录树
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; /* nowjava - 时代Java 提供 */ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map; class WatchRecursive { private WatchService watchService; private final Map<WatchKey, Path> directories = new HashMap<>(); private void registerTree(Path start) throws IOException { /** 来自 时代Java公众号**/ Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { System.out.println("Registering:" + dir); WatchKey key = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); directories.put(key, dir); return FileVisitResult.CONTINUE; } }); } public void watchRNDir(Path start) throws IOException, InterruptedException { watchService = FileSystems.getDefault().newWatchService(); registerTree(start); while (true) { final WatchKey key = watchService.take(); for (WatchEvent<?> watchEvent : key.pollEvents()) { Kind<?> kind = watchEvent.kind(); WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; Path filename = watchEventPath.context(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { final Path directory_path = directories.get(key); final Path child = directory_path.resolve(filename); if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) { registerTree(child); } } System.out.println(kind + " -> " + filename); } boolean valid = key.reset(); if (!valid) { directories.remove(key);