简体   繁体   中英

How to keep monitoring a folder to check newly added/created files in java?

I am using WatchService to keep monitoring if a file get added in directory. I am using following code for it.

public class JNotifyTest {

public static void main(String[] args) {

    //define a folder root
    Path myDir = Paths.get("C:\\Users\\DadMadhR\\Desktop\\temp\\");       

    try {
       WatchService watcher = myDir.getFileSystem().newWatchService();
       myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

       WatchKey watckKey = watcher.take();

       List<WatchEvent<?>> events = watckKey.pollEvents();
       for (WatchEvent event : events) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                System.out.println("Created: " + event.context().toString());
            }
            main(null);
        }

    } catch (Exception e) {
        System.out.println("Error: " + e.toString());
    }
}

}

But here, it's tracking only for files getting added in temp folder, but not in sub folders. Also I am able to print only file name. Is there any way to get file path of newly added/created file?

Also I am calling main function inside main to track each file creation. Is there any replacement or other way for this?

But here, it's tracking only for files getting added in temp folder, but not in sub folders.

Since you're registering the watcher for the root directory only you'll only get notified if that directory is modified. Depending on the underlying filesystem a directory might only be modified if its direct children are modified, ie changes in subdirectory are not propagated upwards.

You could try and register the watcher for any added subdirectory, ie you recursively apply it to the entire hierarchy.

Also I am able to print only file name. Is there any way to get file path of newly added/created file?

Check the WatchEvent.context() method. JavaDoc:

In the case of ENTRY_CREATE, ENTRY_DELETE, and ENTRY_MODIFY events the 
context is a Path that is the relative path between the directory registered
with the watch service, and the entry that is created, deleted, or modified.

That implies you should get the entire path my using the path you registered the event on, the context and the filename.

Also I am calling main function inside main to track each file creation. Is there any replacement or other way for this?

Don't call the method again but use a loop like while(true) along with a break when you want to exit the loop.

Example:

while(true) {
  List<WatchEvent<?>> events = watckKey.pollEvents();
  for( WatchEvent<?> e : events ) {
    //whatever
  }

  if( someConditionToExit ) {
    break;
  }
}

Problems with calling main(null) like you did above:

  • You only call it if you have events, so the application will exit if there are no events to be polled (and the JavaDoc on poll() says it won't wait).
  • You call it for every event, ie if you have 2 events you call main(null) twice.
  • Recursively calling a method without any stop condition like you're doing it will eventually result in a StackOverflowError since every call will add one more entry to the call stack until there's no more space left.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM