[NIO] 디렉토리 모니터링 API(WatchService)
Watching Path
One of the nicest feature of the NIO File API is the WatchService, which can monitor a Path for change to any file or directory in the hierarchy.
import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.List;
/** * @author Steven J.S Min * */ public class WatchingPaths {
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException {
FileSystem fs = FileSystems.getDefault();
Path watchPath = fs.getPath("C:/Temp/1"); WatchService watchService = fs.newWatchService(); watchPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
while (true) { try {
// 지정된 디렉토리에 변경이되는지 이벤트를 모니터링한다. WatchKey changeKey = watchService.take();
List<WatchEvent<?>> watchEvents = changeKey.pollEvents();
for (WatchEvent<?> watchEvent : watchEvents) { // Ours are all Path type events: WatchEvent<Path> pathEvent = (WatchEvent<Path>) watchEvent;
Path path = pathEvent.context(); WatchEvent.Kind<Path> eventKind = pathEvent.kind();
System.out.println(eventKind + " for path: " + path); }
changeKey.reset(); // Important!
} catch (InterruptedException e) { e.printStackTrace(); }
} }
}
|