java USES WatchService to monitor the folder example
- 2020-06-07 04:31:41
- OfStack
Through WatchService API provided by java7 to achieve the monitoring of folders
package service;
import config.Config;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class WatchDirService {
private WatchService watchService;
private boolean notDone = true;
public WatchDirService(String dirPath){
init(dirPath);
}
private void init(String dirPath) {
Path path = Paths.get(dirPath);
try {
watchService = FileSystems.getDefault().newWatchService(); // create watchService
path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE); // Register the events that need to be monitored ,ENTRY_CREATE File creation ,ENTRY_MODIFY File modification ,ENTRY_MODIFY File deletion
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
System.out.print("watch...");
while (notDone){
try {
WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS); // This will be in a wait state , Wait to detect a change in the file under the folder , return WatchKey object
if(watchKey != null){
List<WatchEvent<?>> events = watchKey.pollEvents(); // Gets all of the events
for (WatchEvent event : events){
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW){
// The current disk is not available
continue;
}
WatchEvent<Path> ev = event;
Path path = ev.context();
if(kind == StandardWatchEventKinds.ENTRY_CREATE){
System.out.println("create " + path.getFileName());
}else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
System.out.println("modify " + path.getFileName());
}else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
System.out.println("delete " + path.getFileName());
}
}
if(!watchKey.reset()){
// The process has been closed
System.out.println("exit watch server");
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}
That's all it takes to monitor 1 folder.
Full code address: WatchServerDemo_jb51.rar