Here it is:
Code: Select all
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.*;
public class WatchTest {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Pass a directory to watch as an argument");
System.exit(1);
}
File f = new File(args[0]);
f = f.getCanonicalFile();
Path p = f.toPath();
WatchService watchService = FileSystems.getDefault().newWatchService();
p.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
while(true) {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_CREATE)
System.out.printf("created %s %s\n",key.watchable(), event.context());
else if (event.kind() == ENTRY_MODIFY)
System.out.printf("modified %s %s\n",key.watchable(), event.context());
else if (event.kind() == ENTRY_DELETE) {
System.out.printf("deleted %s %s\n",key.watchable(), event.context());
} else
System.out.println("???");
}
key.reset();
}
}
}
2. Open a command prompt and type "javac -version". If that shows an error, then javac from AdoptOpenJDK isn't in your path, which is fine. It would be inside the bin\ folder in the jdk installation
3. Compile the code above by typing "path\to\javac.exe WatchTest.java"
4. Execute the program by typing "path\to\java.exe -cp . WatchTest \path\to\watch"
Then try dropping and deleting files in the \path\to\watch. The program should print something every time you drop or remove a file. If it doesn't, then we'll have to try different version of Java or start looking at the NAS drivers, or something along those lines.