package monitor; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; public class Monitor { private static Path sharedDirectoryPath; private static WatchKey watchKey; private static WatchService watchService; public static void main(String[] args) { // 모니터링할 파일들을 포함한 디렉터리의 경로를 설정한다 String path = "/Users/Sevas/directoryToBeMonitored"; sharedDirectoryPath = Paths.get(path); try { // FileSystems를 Watch 할 수 있는 인스턴스를 얻는다 watchService = FileSystems.getDefault().newWatchService(); // WatchKey에 WatchService 객체와 감지할 이벤트를 등록한다 watchKey = sharedDirectoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); } catch (IOException e) { e.printStackTrace(); } while(true) { // 이벤트가 발생할 때 마다 콘솔로 출력한다 for(WatchEvent<?> watchEvent : watchKey.pollEvents()) { System.out.println(watchEvent.context() + " " + watchEvent.kind()); } } } }
Result:
Prerequisites for this program:
1) package 이름을 자신의 프로젝트에 맞게 설정
2) main method 내의 path를 모니터링할 자신의 로컬 디렉토리 경로로 설정
위의 전제조건을 갖춘 후 실제로 이 프로그램을 실행시켜보자
그리고 차례로 파일을 생성, 삭제, 수정해보자
watchKey에 등록된 이벤트들이 차례로 감지되는 것을 볼 수 있다
** 지정된 디렉토리 내의 파일들의 생성, 수정, 삭제가 감지가 필요한곳은 과연 어디일까..?