Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java监视文件夹和监视文件夹中的所有文件和文件夹完成下载时的操作_Java_Watch - Fatal编程技术网

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

Java监视文件夹和监视文件夹中的所有文件和文件夹完成下载时的操作,java,watch,Java,Watch,我正在尝试编写使用watch文件夹处理媒体文件的工具。Oracle示例演示了如何知道文件夹中何时有更改。但问题是,我不知道所有媒体何时完成上传。因此,例如,当一张SD卡包含不同文件夹中包含多个文件的介质时,我需要能够在所有文件和子文件夹出现后处理介质。介质并不总是存储在单个文件中,但可能有侧车文件,因此两组文件都需要存在,以便正确处理文件。有人能告诉我如何知道所有文件和子文件夹都已复制到监视文件夹中吗 这是我对WatchDir稍加修改的版本,其中包括日志记录: public class Watc

我正在尝试编写使用watch文件夹处理媒体文件的工具。Oracle示例演示了如何知道文件夹中何时有更改。但问题是,我不知道所有媒体何时完成上传。因此,例如,当一张SD卡包含不同文件夹中包含多个文件的介质时,我需要能够在所有文件和子文件夹出现后处理介质。介质并不总是存储在单个文件中,但可能有侧车文件,因此两组文件都需要存在,以便正确处理文件。有人能告诉我如何知道所有文件和子文件夹都已复制到监视文件夹中吗

这是我对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();
    }
}

也许你做不到。根据,WatchService仅提供以下事件:

因此,您将不知道是否有新文件要创建/复制到您的目录中

也许你可以考虑一些变通办法:

设置一个超时时间,如果没有创建新文件,则考虑文件传输完成并开始执行该工作。 让您的应用程序来处理复制,这样它就可以知道进度,并在复制完所有文件后触发工作。
谢谢你的建议@TKJohn。我可以判断一个文件何时完成上载,但问题是我使用的媒体通常由多个文件组成,例如,可能有一个包含与媒体文件关联的元数据的侧车文件。所以我不能处理单个文件。关于你的第二个建议,复制可以通过其他3个应用程序进行,因此我无法控制复制过程。我个人会选择超时方法,因为如果它是桌面应用程序,用户通过你的应用程序复制文件是一件非常痛苦的事,除非你的应用程序是文件管理器@凯伦,你不必为一个文件工作。一般的想法是在你的应用程序中有一个计数器,比如说,每秒钟,然后听EngyTyCube和EngyIy修改事件——如果没有发生一段时间,要考虑拷贝的完成,然后你就可以开始处理了。我认为,您需要自己查看多少时间,因为这取决于文件大小。
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. ```