Java-目录的FileWatcher-重命名实现

时间:2018-06-21 18:58:41

标签: java

我有以下代码,该代码以递归方式监视目录中的文件。重命名文件时的输出如下所示:

ENTRY_DELETE: C:\Users\Robin\Desktop\cloud\Name1.txt
ENTRY_CREATE: C:\Users\Robin\Desktop\cloud\Name2.txt

由于这两个事件都在最长200毫秒内发生,所以我想到了一个计时器,该计时器检查在200毫秒内是否删除并创建了一个文件,以确保仅重命名该文件。有人可以告诉我该怎么做吗?

我的代码如下:

public class Cloud {

        private final WatchService watcher;
    private final Map<WatchKey, Path> keys;


    Cloud(Path dir) throws IOException {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<WatchKey, Path>();

        walkAndRegisterDirectories(dir);
    }

    private void registerDirectory(Path dir) throws IOException 
    {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        keys.put(key, dir);
    }


    private void walkAndRegisterDirectories(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 {
                registerDirectory(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }

    void processEvents() {
        for (;;) {

            // wait for key to be signalled
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

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

            for (WatchEvent<?> event : key.pollEvents()) {
                @SuppressWarnings("rawtypes")
                WatchEvent.Kind kind = event.kind();

                // Context for directory entry event is the file name of entry
                @SuppressWarnings("unchecked")
                Path name = ((WatchEvent<Path>)event).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 (kind == ENTRY_CREATE) {
                    try {
                        if (Files.isDirectory(child)) {
                            walkAndRegisterDirectories(child);
                        }
                    } catch (IOException x) {
                        // do something useful
                    }
                }
            }

            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid) {
                keys.remove(key);

                // all directories are inaccessible
                if (keys.isEmpty()) {
                    break;
                }
            }
        }
    }


    public static void main(String[] args) throws IOException, InterruptedException {

        Path dir = Paths.get("C:/Users/Robin/Desktop/cloud");
    new Cloud(dir).processEvents();


    }    

}

0 个答案:

没有答案