자바(Java)
자바 폴더 실시간 모니터링
xemaker
2019. 7. 18. 16:24
git source 소스 링크
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;
import java.time.LocalDateTime;
public class FileObserver {
public static void main(String[] args) {
String targetDirectory = "D:\\";
observeFileCreated(targetDirectory);
}
private static void observeFileCreated(String targetDirectory) {
Path faxFolder = Paths.get(targetDirectory);
try {
WatchService fileWatchService = FileSystems.getDefault().newWatchService();
faxFolder.register(fileWatchService, StandardWatchEventKinds.ENTRY_CREATE);
boolean valid = true;
do {
WatchKey watchKey = fileWatchService.take();
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind kind = event.kind();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("start to notify file Created :" + fileName + " , time : " + LocalDateTime.now());
}
}
valid = watchKey.reset();
} while (valid);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
결과
D드라이브에 폴더가 만들어 졌을때
start to notify file Created :새 폴더 , time : 2020-07-03T17:56:38.133
D드라이브에 파일이 만들어졌을때
start to notify file Created :새 텍스트문서 , time : 2020-07-03T17:56:44.964