Created
March 11, 2016 01:03
-
-
Save mcqueenorama/068d9ecc84dcb1a59fd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void test() throws Exception { | |
Path wd = Files.createTempDirectory("watcher-test"); | |
SyncWatcher sw = new SyncWatcher(wd); | |
// sw.watch(); | |
(new Thread(sw.runner)).start(); | |
Thread.sleep(10000); | |
Path lameFile = Paths.get(wd.toString(), "some file"); | |
assertFalse(lameFile.toFile().exists()); | |
Files.write(lameFile, "lame text".getBytes()); | |
assertTrue(lameFile.toFile().exists()); | |
Files.delete(lameFile); | |
Thread.sleep(10000); | |
} | |
// | |
//class | |
// | |
public class SyncWatcher { | |
private final Path pathToWatch; | |
private static final Logger LOGGER = Logger.getLogger(SyncWatcher.class.getName()); | |
public Runner runner; | |
public SyncWatcher(Path pathToWatch) { | |
LOGGER.log(Level.INFO, String.format("QQQ:init")); | |
this.pathToWatch = pathToWatch; | |
runner = new Runner(this); | |
} | |
public void watch() throws Exception { | |
DirectoryWatcher watcher = DirectoryWatcher.builder().directory(pathToWatch).listener(new DirectoryChangeListener() { | |
@Override | |
public void onCreate(Path path) throws IOException { | |
// process create | |
LOGGER.log(Level.INFO, String.format("QQQ:onCreate")); | |
} | |
@Override | |
public void onModify(Path path) throws IOException { | |
LOGGER.log(Level.INFO, String.format("QQQ:onModify")); | |
// process modifiy | |
} | |
@Override | |
public void onDelete(Path path) throws IOException { | |
// process delete | |
LOGGER.log(Level.INFO, String.format("QQQ:onDelete")); | |
} | |
}).build(); | |
watcher.processEvents(); | |
} | |
public class Runner implements Runnable { | |
private SyncWatcher sw; | |
public Runner(SyncWatcher sw) { | |
this.sw = sw; | |
} | |
public void run() { | |
System.out.println("Hello from a thread!"); | |
try { | |
sw.watch(); | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment