Advertisement
Guest User

Untitled

a guest
Apr 28th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. public class Main {
  2.  
  3. public static void main(String[] args) throws Exception {
  4. new DirWatcher(ClassManager.DIR).watch(new WatcherHandler() {
  5.  
  6. @Override
  7. public void handler() {
  8. //todo
  9.  
  10. }
  11. });
  12. }
  13.  
  14. }
  15.  
  16.  
  17. import java.io.IOException;
  18. import java.nio.file.FileSystems;
  19. import java.nio.file.Paths;
  20. import java.nio.file.StandardWatchEventKinds;
  21. import java.nio.file.WatchEvent;
  22. import java.nio.file.WatchEvent.Kind;
  23. import java.nio.file.WatchKey;
  24. import java.nio.file.WatchService;
  25.  
  26. public class DirWatcher {
  27.  
  28. private WatchService service;
  29.  
  30. public DirWatcher(String filePath) throws IOException {
  31. service = FileSystems.getDefault().newWatchService();
  32. // register create event
  33. Paths.get(filePath).register(service, StandardWatchEventKinds.ENTRY_CREATE);
  34.  
  35. }
  36.  
  37. public void watch(WatcherHandler handler) throws InterruptedException {
  38. while (true) {
  39. WatchKey key = service.take();
  40. for (WatchEvent<?> event : key.pollEvents()) {
  41. Kind<?> kind = event.kind();
  42. if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
  43. handler.handler();
  44. }
  45. }
  46. key.reset();
  47. }
  48. }
  49.  
  50. }
  51.  
  52. public interface WatcherHandler {
  53. public void handler();
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement