WatchService and SwingWorker: how to do it correctly?

Because your background thread is devoted entirely to watching, take() is the right choice. It effectively hides the platform dependent implementation, which may either forward or poll. One of the poll() methods would be appropriate if, for example, your background thread also needed to examine other queues in series with the WatchService. Addendum: Because the … Read more

Can I watch for single file change with WatchService (not the whole directory)?

Just filter the events for the file you want in the directory: final Path path = FileSystems.getDefault().getPath(System.getProperty(“user.home”), “Desktop”); System.out.println(path); try (final WatchService watchService = FileSystems.getDefault().newWatchService()) { final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); while (true) { final WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { //we only register “ENTRY_MODIFY” so the context is always … Read more