Skip to content

Instantly share code, notes, and snippets.

@PrasannaC
Last active September 20, 2019 06:21
Show Gist options
  • Save PrasannaC/06aef2e1ef155b04a61d0ec0265d5f1b to your computer and use it in GitHub Desktop.
Save PrasannaC/06aef2e1ef155b04a61d0ec0265d5f1b to your computer and use it in GitHub Desktop.
Basic Watcher class in JAVA for reference.
/*
This class is a mere template and can be modified for better methods of access of lists and can be written in a more elegant manner.
It is to demonstrate the basics of writing your own watcher, since the JAVA API was causing issues regarding locking of
files in a directory when multiple events are generated.
*/
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class Watcher {
private String dir;
// Contains a list of files which are now old/already present.
public static List<String> oldFiles;
// Queue to access list of new files in the directory.
public static ConcurrentLinkedQueue<String> newFiles;
// Set the directory to watch
public Watcher(String dir) {
this.dir = dir;
oldFiles = new ArrayList<>();
newFiles = new ConcurrentLinkedQueue<>();
}
// Spawn a background thread to keep track of files being added in the directory.
public void start() {
new Thread(new Runnable() {
// Helper function to list files in a directory.
private List<String> fileList(String directory) {
List<String> fileNames = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(directory))) {
for (Path path : directoryStream) {
fileNames.add(path.toAbsolutePath().toString());
}
} catch (IOException ex) {
ex.printStackTrace();
}
return fileNames;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!dir.equals(null) && dir.length() != 0) {
List<String> files = fileList(dir);
// Handle cases: 1st scan and subsequent scans.
if (oldFiles.isEmpty()) {
newFiles.addAll(files);
} else {
if (files.removeAll(oldFiles))
newFiles.addAll(files);
}
}
}
}
}).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment