Java监视文件夹和监视文件夹中的所有文件和文件夹下载完成后的操作

时间:2019-02-08 10:12:59

标签: java watch

我正在尝试编写一种使用watch文件夹处理媒体文件的工具。 Oracle示例WatchDir演示了如何知道文件夹中何时有更改。但是,这样做的问题是我不知道所有媒体何时完成上传。因此,例如,当将包含媒体的SD卡(包含在不同文件夹中的多个文件)拖到监视文件夹中时,一旦所有文件和子文件夹都存在,我就必须能够处理媒体。介质并不总是仅存储在单个文件中,而是可能具有sidecar文件,因此需要同时存在两组文件才能正确处理文件。谁能建议我如何知道所有文件和子文件夹已完成复制到监视文件夹中?

这是我对WatchDir进行的稍微修改的版本,其中包括日志记录:

public class WatchDir {

    private final WatchService watcher;
    private final Map<WatchKey,Path> keys;
    private final boolean recursive;
    private boolean trace = false;

    @SuppressWarnings("unchecked")
    static <T> WatchEvent<T> cast(WatchEvent<?> event) {
        return (WatchEvent<T>)event;
    }

    /**
     * Register the given directory with the WatchService
     */
    private void register(Path dir) throws IOException {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        if (trace) {
            Path prev = keys.get(key);
            if (prev == null) {
                System.out.format("register: %s%n", dir);
            } else {
                if (!dir.equals(prev)) {
                    System.out.format("update: %s -> %s%n", prev, dir);
                }
            }
        }
        keys.put(key, dir);
    }

    /**
     * Register the given directory, and all its sub-directories, with the
     * WatchService.
     */
    private void registerAll(final Path start) throws IOException {
        // register directory and sub-directories
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException
            {
                register(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    /**
     * Creates a WatchService and registers the given directory
     */
    WatchDir(Path dir, boolean recursive) throws IOException {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<WatchKey,Path>();
        this.recursive = recursive;

        if (recursive) {
            System.out.format("Scanning %s ...\n", dir);
            registerAll(dir);
            System.out.println("Done.");
        } else {
            register(dir);
        }

        // enable trace after initial registration
        this.trace = true;
    }

    /**
     * Process all events for keys queued to the watcher
     */
    void processEvents() {
        System.out.println("process event");
        boolean processing = false;
        for (;;) {
            System.out.println("loop");
            // wait for key to be signalled
            WatchKey key;
            try {
                processing = false;
                System.out.println("about to take");
                key = watcher.take();
                processing = true;

            } catch (InterruptedException x) {
                System.out.println("take interrupted");
                return;
            }

            Path dir = keys.get(key);
            if (dir == null) {
                System.err.println("WatchKey not recognized!!");
                continue;
            }

            for (WatchEvent<?> event: key.pollEvents()) {

                System.out.println("poll");
                WatchEvent.Kind kind = event.kind();

                // TBD - provide example of how OVERFLOW event is handled
                if (kind == OVERFLOW) {
                    System.out.println("Overflow");
                    continue;
                }

                // Context for directory entry event is the file name of entry
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);

                // print out event
                System.out.format("%s: %s\n", event.kind().name(), child);

                // if directory is created, and watching recursively, then
                // register it and its sub-directories
                if (recursive && (kind == ENTRY_CREATE)) {
                    try {
                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                            registerAll(child);
                        }
                    } catch (IOException x) {
                        // ignore to keep sample readable
                        System.out.println("ex: " + x.getMessage());
                    }
                }
            }

            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid) {
                keys.remove(key);
                System.out.println("finished this set of files");
                // all directories are inaccessible
                if (keys.isEmpty()) {
                    break;
                }
            }
            if (processing) {
                System.out.println("processing files...");
            } else {
                System.out.println("not processing files");
            }
            System.out.println("End of loop\n\n");
        }
    }

    static void usage() {
        System.err.println("usage: java WatchDir [-r] dir");
        System.exit(-1);
    }

    public static void main(String[] args) throws IOException {
        // parse arguments
        if (args.length == 0 || args.length > 2)
            usage();
        boolean recursive = false;
        int dirArg = 0;
        if (args[0].equals("-r")) {
            if (args.length < 2)
                usage();
            recursive = true;
            dirArg++;
        }

        // register directory and process its events
        Path dir = Paths.get(args[dirArg]);
        new WatchDir(dir, recursive).processEvents();
    }
}

1 个答案:

答案 0 :(得分:0)

也许您不能那样做。根据{{​​3}},WatchService仅提供了以下事件:

static WatchEvent.Kind<Path>  ENTRY_DELETE Directory entry deleted.
static WatchEvent.Kind<Path>  ENTRY_MODIFY Directory entry modified.
static WatchEvent.Kind<Object>    OVERFLOW A special event to indicate that events may have been lost or discarded. ```

所以您将不知道是否有新文件要创建/复制到您的目录中。

也许您可以考虑一些解决方法:

  • 设置一个超时时间,如果该时间没有创建新文件,请考虑文件传输已完成并开始工作。
  • 让您的应用程序处理副本,以便在复制完所有文件后知道进度并触发工作。