简体   繁体   English

递归监视Java中的目录和所有子目录

[英]Recursively monitor a directory and all sub directories in java

I need to monitor a given directory and all its sub directories for changes (Especially addition of files and directories). 我需要监视给定目录及其所有子目录的更改(尤其是文件和目录的添加)。

My current code is as follows 我当前的代码如下

Path watchFolder = Paths.get("D:/watch");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
            watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);
            watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

    boolean valid = true;
    do {
        WatchKey watchKey = watchService.take();

        for (WatchEvent event : watchKey.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind)) {
                String fileName = event.context().toString();
                System.out.println("File Created:" + fileName);
            }
        }
        valid = watchKey.reset();

    } while (valid);

This code is only able to monitor the parent directory changes. 此代码只能监视父目录的更改。 If I add a directory in the parent directory, it is able to fire the event. 如果我在父目录中添加目录,则可以触发该事件。 But, if I add a file inside sub-directory, it is not able detect. 但是,如果我在子目录中添加文件,则无法检测到。

FYI : I also tried JNotify, but it keeps saying java.lang.UnsatisfiedLinkError: no jnotify_64bit in java.library.path 仅供参考:我也尝试过JNotify,但它一直说java.lang.UnsatisfiedLinkError: no jnotify_64bit in java.library.path

Is there any better solution than these? 有没有比这些更好的解决方案?

I would like to encourage you to give another try. 我想鼓励你给闯闯。 It nicely reports changes in subdirectories and looks more resource efficient than creating a load of WatchKey s for each and every directory you want to track. 与为要跟踪的每个目录创建WatchKey的负载相比,它很好地报告了子目录中的更改,并且看起来更加节省资源。

As for your UnsatisfiedLinkError , see How to set the java.library.path from Eclipse . 至于您的UnsatisfiedLinkError ,请参阅如何从Eclipse设置java.library.path I placed jnotify_64bit.dll (Windows here) in my project's base dir, and it worked. 我将jnotify_64bit.dll (此处为Windows)放置在项目的基本目录中,并且可以正常工作。 YMMV. YMMV。

From your question, I assume that your requirement is to poll the directory and when some file comes do something, meaning call some method. 从您的问题出发,我假设您的要求是轮询目录,并且在某些文件出现时执行某些操作,这意味着调用某种方法。

If I have understood correctly then you should try JPoller which reduces the complexity and does what you need. 如果我理解正确,那么您应该尝试JPoller ,它可以降低复杂性并满足您的需求。 It also allows you to set polling interval and provides you with a handful of callback methods. 它还允许您设置轮询间隔,并提供了一些回调方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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