자바(Java)

자바 폴더 실시간 모니터링

xemaker 2019. 7. 31. 21:46

public class Monitor {

private static Path sharedDirectoryPath;
private static WatchKey watchKey;
private static WatchService watchService;

public static void main(String[] args) throws Exception {
System.out.println("Start");
String path = "D:\\test";
String pathFile = "D:\\test\\test.txt";
sharedDirectoryPath = Paths.get(path);
try{
watchService = FileSystems.getDefault().newWatchService();
watchKey = sharedDirectoryPath.register(watchService
, StandardWatchEventKinds.ENTRY_CREATE
, StandardWatchEventKinds.ENTRY_DELETE
, StandardWatchEventKinds.ENTRY_MODIFY);

}catch(IOException e){
e.printStackTrace();
}
while(true){

 for(WatchEvent&lt?> watchEvent : watchKey.pollEvents()){ 
//System.out.println(watchEvent.context() + " " + watchEvent.kind());
if( watchEvent.kind() ==  StandardWatchEventKinds.ENTRY_CREATE ){
System.out.println("create");
try{
Thread.sleep(1);
File file = new File(pathFile);
FileReader filereader = new FileReader(file);
BufferedReader br = new BufferedReader(filereader);
String line = "";
while( (line = br.readLine()) != null ){
System.out.println(line);
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}
}