如何判断文件何时

如何判断文件何时

本文介绍了如何判断文件何时“完成"复制到监视目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WatchService API 来观看一个目录,并在用户使用时获取 ENTRY_CREATE 事件开始将文件复制到目录中.不过,我正在处理的文件可能很大,我想知道副本何时完成.是否有任何内置的 Java API 可以用来完成此操作,或者我最好只跟踪创建的文件的大小并在大小停止增长时开始处理?

I'm using the WatchService API to watch a directory, and getting ENTRY_CREATE events when a user starts copying a file into the directory. The files I'm working with can be large, though, and I'd like to know when the copy is finished. Is there any built in java API I can use to accomplish this, or am I best off to just keep track of the created files' size and start processing when the size stops growing?

这是我的示例代码:

package com.example;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class Monitor {
    public static void main(String[] args) {
        try {
            String path = args[0];

            System.out.println(String.format( "Monitoring %s", path  ));
            WatchService watcher = FileSystems.getDefault().newWatchService();
            Path watchPath = FileSystems.getDefault().getPath(path);

            watchPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);

            while (true) {
                WatchKey key = watcher.take();
                for (WatchEvent<?> event: key.pollEvents()) {
                    Object context = event.context();
                    System.out.println( String.format( "Event %s, type %s", context, event.kind() ));

                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

产生这个输出:

Monitoring /Users/ericcobb/Develop/watch
Event .DS_Store, type ENTRY_MODIFY
Event 7795dab5-71b1-4b78-952f-7e15a2f39801-84f3e5daeca9435aa886fbebf7f8bd61_4.mp4, type ENTRY_CREATE

推荐答案

创建条目后,您将收到一个 ENTRY_CREATE 事件.对于随后的每次修改,您将获得 ENTRY_MODIFY 事件.复制完成后,您将收到 ENTRY_MODIFY 通知.

When an entry is created, you will get an ENTRY_CREATE event. For every subsequent modification, you will get an ENTRY_MODIFY event. When copying is completed, you will be notified with an ENTRY_MODIFY.

这篇关于如何判断文件何时“完成"复制到监视目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:47