Skip to content

Instantly share code, notes, and snippets.

@ygrenzinger
Created February 26, 2016 15:04
Show Gist options
  • Save ygrenzinger/867e2fda2c71ba0135b5 to your computer and use it in GitHub Desktop.
Save ygrenzinger/867e2fda2c71ba0135b5 to your computer and use it in GitHub Desktop.
Watch change in file
import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RunnableFuture;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.nio.file.StandardWatchEventKinds.*;
public class Watcher implements Runnable {
private final WatchService watcher;
private WatchKey watchKey;
private final Consumer<Path> consumer;
private Watcher(Consumer<Path> consumer) throws IOException {
this.consumer = consumer;
watcher = FileSystems.getDefault().newWatchService();
}
public static Watcher create(Consumer<Path> consumer) throws IOException {
return new Watcher(consumer);
}
public Watcher watchDirectory(Path directory) throws IOException {
directory.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
return this;
}
public List<Path> getModifiedFiles() throws Exception {
watchKey = watcher.take();
List<Path> modifiedPaths = watchKey.pollEvents().stream()
.filter(onlyCreatedOrModifiedFiles())
.map(watchEvent -> (WatchEvent<Path>) watchEvent)
.map(pathEvent -> pathEvent.context())
.collect(Collectors.toList());
return modifiedPaths;
}
private Predicate<WatchEvent<?>> onlyCreatedOrModifiedFiles() {
return watchEvent -> watchEvent.kind() == ENTRY_CREATE || watchEvent.kind() == ENTRY_MODIFY;
}
private boolean reinit() {
return watchKey.reset();
}
@Override
public void run() {
try {
do {
getModifiedFiles().forEach(consumer);
} while (reinit());
} catch (Exception e) {
e.printStackTrace();
}
}
}
@ygrenzinger
Copy link
Author

`import java.io.IOException;
import java.nio.file.Paths;

/**

  • Created by yannickgrenzinger on 26/02/2016.
    */
    public class Main {

    public static void main(String... arg) throws IOException, InterruptedException {
    Watcher watcher = Watcher.create(path -> System.out.println("Modified file : " + path));
    watcher.watchDirectory(Paths.get("/Users/yannickgrenzinger/Lab/code/ruby/"));
    Thread th = new Thread(watcher, "FileWatcher");
    th.start();
    }
    }
    `

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment