자바(Java)/어플리케이션
[java] 자바 디렉토리 모니터링
xemaker
2020. 7. 6. 08:45
자바 윈도우 환경에서 디렉토리 (폴더)에 파일이 생성되거나 삭제, 변경되었을 시 모니터링 하고 있다가 알람등을 할 수 있는 프로그램 입니다.
smtp를 연결하면 메일보내기 등도 할 수 있겠네요.. 구글 smtp를 사용해서 메일보내는 전체 소스도 이 블로그에 있으니 참고하시면 될듯 합니다.
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 {
System.out.println("Starting...");
WatchService fileWatchService = FileSystems.getDefault().newWatchService();
faxFolder.register(fileWatchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.OVERFLOW
);
boolean valid = true;
do {
WatchKey watchKey = fileWatchService.take();
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind kind = event.kind();
System.out.println(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());
// Desktop.getDesktop().open(new File("C:\\test.mp4"));
}else if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("start to notify file Deleteed :" + fileName + " , time : " + LocalDateTime.now());
}else if(StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())){
String fileName = event.context().toString();
System.out.println("start to notify file modified :" + fileName + " , time : " + LocalDateTime.now());
}else if(StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())){
String fileName = event.context().toString();
System.out.println("start to notify file deleted :" + fileName + " , time : " + LocalDateTime.now());
}else if(StandardWatchEventKinds.OVERFLOW.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("start to notify OVERFLOW time : " + LocalDateTime.now());
}else{
System.out.println("UNKNOWN EVENT ......");
}
}
valid = watchKey.reset();
} while (valid);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
결과
Starting...
ENTRY_CREATE
start to notify file Created :새 텍스트 문서 - 복사본 - 복0사본 - 복사본.txt , time : 2020-07-06T08:41:25.958
ENTRY_MODIFY
start to notify file modified :새 텍스트 문서 - 복사본 - 복0사본 - 복사본.txt , time : 2020-07-06T08:41:25.959
ENTRY_DELETE
start to notify file Deleteed :새 텍스트 문서 - 복사본 - 복0사본 - 복사본.txt , time : 2020-07-06T08:41:31.216
결과에서 알 수 있듯이 D 드라이브 루트에 파일이 생성될때, 수정될때(생성되도 수정되는거니 동시에 찍히네요) 삭제될때 찍히는것을 볼 수 있습니다.