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(); }
} }
}
|
'Java > Input/Output Facilities' 카테고리의 다른 글
[NIO] Stream 파일복사 vs Buffer/Channel 파일복사 (0) | 2013.11.14 |
---|---|
[NIO] NIO의 기본 개념 (0) | 2013.11.14 |
Filter Stream과 Decorator 패턴 (0) | 2013.11.11 |
바이트 Stream과 문자 스트림 (0) | 2013.11.11 |
[바이트 스트림] 데이터 압축 및 해제 - GZIPOutputStream & GZIPInputStream 사용 (0) | 2013.02.11 |