如果重命名(OSX)

时间:2017-10-03 02:21:53

标签: java macos

我试图在MacOS(High Sierra)上设置WatchService,除非我重命名dir,否则它似乎正常工作。作为一个例子,我重命名"测试"到"你好"而这就是我得到的:

ENTRY_CREATE: /Users/david/Desktop/watchme/hello
update: /Users/david/Desktop/watchme/test -> /Users/david/Desktop/watchme/hello
ENTRY_DELETE: /Users/david/Desktop/watchme/test

我希望看到:

register: /Users/david/Desktop/watchme/hello

但这并没有发生,所以当我修改" hello"内的任何内容时,我得到的唯一回应是:

ENTRY_MODIFY: /Users/david/Desktop/watchme/hello

没有关于"你好"

内的文件或文件夹

我直接从Oracle复制了以下代码,除了对attrs进行硬编码以外,我可以在Idea中运行它:

import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;

/**
 * Example to watch a directory (or tree) for changes to files.
 */

public class WatchDir {

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

    @SuppressWarnings("unchecked")
    private 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
     */
    private WatchDir(Path dir, boolean recursive) throws IOException {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<>();
        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
     */
    private 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()) {
                WatchEvent.Kind kind = event.kind();

                // TBD - provide example of how OVERFLOW event is handled
                if (kind == 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(child.toString().contains("testdir")) {
                    System.out.println("This is an update");
                }

                // 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 readbale
                    }
                }
            }

            // 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;
                }
            }
        }
    }

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

    @SuppressWarnings("ParameterCanBeLocal")
    public static void main(String[] args) throws IOException {
        // parse arguments
        args = new String[2];                     // Added for debug
        args[0] = "-r";                           // Added for debug
        args[1] = "/Users/david/Desktop/watchme"; // Added for debug
        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 :(得分:1)

这是一个有趣的问题。我尝试在自己的Mac上获得相同的结果。

当我们将 test 重命名为 hello 时,操作系统首先创建 hello ,然后删除 test ,两者都< em> watchme 和 test 将获得活动。 watchme 文件夹的WatchKey获取ENTRY_CREATE和ENTRY_DELETE事件。 在此步骤中,虽然新的目录名称为 hello ,但在此代码之后

WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

我们获得的密钥仍然是 test 的监视密钥,这就是我们在控制台中看到更新日志的原因。

ENTRY_CREATE: /Users/david/Desktop/watchme/hello
update: /Users/david/Desktop/watchme/test -> /Users/david/Desktop/watchme/hello
ENTRY_DELETE: /Users/david/Desktop/watchme/test
test 的WatchKey也收到了一个事件。但是这个事件是一个无效的事件,密钥(事实上这是 hello 的watchKey现在)将从密钥映射中删除。因此, hello 文件夹的更改将不会在控制台中显示任何内容。

这是有趣的事情。当输入目录是 hello 时,为什么我们得到 test 的watchKey。当我调试代码时,请在

处停止它
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

收到 hello 的ENTRY_CREATE事件一段时间后,我得到 hello 的密钥而不是 test 的密钥和注册日志不更新日志。当调用dir.register方法时,我们似乎无法立即看到 hello 文件夹。我不知道操作系统在重命名文件夹时会做什么,希望别人回复。

这是我在processEvents添加了测试代码的日志,您可以亲自尝试。

private 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;
        } else {
            System.out.println("CurrentDir=" + dir.getFileName() + " keySize=" + keys.size() + " valid=" + key.isValid());
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            // TBD - provide example of how OVERFLOW event is handled
            if (kind == 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 readbale
                }
            }
        }
        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            System.out.println("Remove From keys");
            keys.remove(key);
            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}