|
14 | 14 |
|
15 | 15 | import java.io.File; |
16 | 16 | import java.io.IOException; |
| 17 | +import java.nio.file.FileSystems; |
17 | 18 | import java.nio.file.Files; |
18 | 19 | import java.nio.file.Path; |
| 20 | +import java.nio.file.StandardWatchEventKinds; |
| 21 | +import java.nio.file.WatchEvent; |
| 22 | +import java.nio.file.WatchKey; |
| 23 | +import java.nio.file.WatchService; |
| 24 | +import java.util.HashMap; |
| 25 | +import java.util.Map; |
19 | 26 | import java.util.stream.Stream; |
20 | 27 |
|
21 | 28 | public class DebugUtils { |
@@ -69,4 +76,67 @@ private static void listFilesRecursively(Path directoryPath) { |
69 | 76 | e.printStackTrace(); |
70 | 77 | } |
71 | 78 | } |
| 79 | + |
| 80 | + public static void watchDirectory(Path directoryPath) { |
| 81 | + |
| 82 | + Thread thread = new Thread(() -> { |
| 83 | + try { |
| 84 | + WatchService watchService = FileSystems.getDefault().newWatchService(); |
| 85 | + Map<WatchKey, Path> keyPathMap = new HashMap<>(); |
| 86 | + |
| 87 | + // Register the directory and all its subdirectories |
| 88 | + registerAll(directoryPath, watchService, keyPathMap); |
| 89 | + |
| 90 | + LOGGER.warn("Watching directory: {}", directoryPath); |
| 91 | + |
| 92 | + while (true) { |
| 93 | + WatchKey key = watchService.take(); |
| 94 | + Path dir = keyPathMap.get(key); |
| 95 | + |
| 96 | + for (WatchEvent<?> event : key.pollEvents()) { |
| 97 | + WatchEvent.Kind<?> kind = event.kind(); |
| 98 | + Path name = (Path) event.context(); |
| 99 | + Path child = dir.resolve(name); |
| 100 | + |
| 101 | + LOGGER.warn("Event kind: {}. File affected: {}", kind, child); |
| 102 | + |
| 103 | + if (kind == StandardWatchEventKinds.ENTRY_CREATE) { |
| 104 | + if (Files.isDirectory(child)) { |
| 105 | + registerAll(child, watchService, keyPathMap); |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + boolean valid = key.reset(); |
| 111 | + if (valid == false) { |
| 112 | + keyPathMap.remove(key); |
| 113 | + if (keyPathMap.isEmpty()) { |
| 114 | + break; |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + } catch (IOException | InterruptedException e) { |
| 119 | + e.printStackTrace(); |
| 120 | + } |
| 121 | + }); |
| 122 | + |
| 123 | + thread.start(); |
| 124 | + |
| 125 | + } |
| 126 | + |
| 127 | + private static void registerAll(Path start, WatchService watchService, Map<WatchKey, Path> keyPathMap) throws IOException { |
| 128 | + Files.walk(start).filter(Files::isDirectory).forEach(path -> { |
| 129 | + try { |
| 130 | + WatchKey key = path.register( |
| 131 | + watchService, |
| 132 | + StandardWatchEventKinds.ENTRY_CREATE, |
| 133 | + StandardWatchEventKinds.ENTRY_DELETE, |
| 134 | + StandardWatchEventKinds.ENTRY_MODIFY |
| 135 | + ); |
| 136 | + keyPathMap.put(key, path); |
| 137 | + } catch (IOException e) { |
| 138 | + e.printStackTrace(); |
| 139 | + } |
| 140 | + }); |
| 141 | + } |
72 | 142 | } |
0 commit comments