Nisha
Nisha

Reputation: 91

How to implement file watcher to Watch multiple directories

I need to monitor multiple folders for new file notification. I tried for single directory its working fine.
My folder structure looks like
Path path = Paths.get("c:\users\Test"); Path path1 = Paths.get("c:\users\test1"); Path path2 = Paths.get("c:\users\test2");

public static void watchOutBoundDirectory(Path path) {
        String newFile = null;
        try {
            Boolean isFolder = (Boolean) Files.getAttribute(path, "basic:isDirectory", NOFOLLOW_LINKS);
            if (!isFolder) {
                throw new IllegalArgumentException("Path: " + path + " is not a folder");
            }
        } catch (IOException ioe) {
            // Folder does not exists
            ioe.printStackTrace();
        }
        // We obtain the file system of the Path
        FileSystem fs = path.getFileSystem();
        try (WatchService service = fs.newWatchService()) {
            path.register(service, ENTRY_CREATE);
            WatchKey key = null;
            while (true) {
                key = service.take();
                Kind<?> kind = null;
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    kind = watchEvent.kind();
                    if (OVERFLOW == kind) {
                        continue; 
                    } else if (ENTRY_CREATE == kind) {
                        Path newPath = ((WatchEvent<Path>) watchEvent).context();
                        Path fullPath = path.resolve(newPath);
                        String newFile = fullPath.toString();
                    }
                }

                if (!key.reset()) {
                    break; // loop
                }
            }

        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }

    }

I tried registering the each directory to watcher. WatchKey key1 = path1.register(watcher, ENTRY_CREATE); WatchKey key2 = path2.register(watcher, ENTRY_CREATE); i want to monitor multiple folders for incoming events when program starts. Monitor the folders parallelly till i stop the program. how to implement?

Thanks in advance. Please help Please help

Upvotes: 1

Views: 2666

Answers (2)

Roger Dwan
Roger Dwan

Reputation: 770

while (true) {
  ....
}

Since you have an infinite loop, once you call the watchOutBoundDirectory static function. It will never escape the scope unless you disable the watcher.

Therefore either using multi-thread for each path or passing an array of path to watchOutBoundDirectory and check each path inside the while(true) scope.

Upvotes: 1

Youssef NAIT
Youssef NAIT

Reputation: 1530

If you want to monitor more than one folder, I think that a good solution would be to use a multi-threading program, each thread will monitor a folder.

Upvotes: 0

Related Questions