Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) throws Exception {
- new DirWatcher(ClassManager.DIR).watch(new WatcherHandler() {
- @Override
- public void handler() {
- //todo
- }
- });
- }
- }
- import java.io.IOException;
- import java.nio.file.FileSystems;
- import java.nio.file.Paths;
- import java.nio.file.StandardWatchEventKinds;
- import java.nio.file.WatchEvent;
- import java.nio.file.WatchEvent.Kind;
- import java.nio.file.WatchKey;
- import java.nio.file.WatchService;
- public class DirWatcher {
- private WatchService service;
- public DirWatcher(String filePath) throws IOException {
- service = FileSystems.getDefault().newWatchService();
- // register create event
- Paths.get(filePath).register(service, StandardWatchEventKinds.ENTRY_CREATE);
- }
- public void watch(WatcherHandler handler) throws InterruptedException {
- while (true) {
- WatchKey key = service.take();
- for (WatchEvent<?> event : key.pollEvents()) {
- Kind<?> kind = event.kind();
- if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
- handler.handler();
- }
- }
- key.reset();
- }
- }
- }
- public interface WatcherHandler {
- public void handler();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement