不在linux下工作的Java监视服务不适用于eclipse修改的文件

时间:2016-07-12 10:01:12

标签: java eclipse

我正在尝试编写java程序来实时跟踪eclipse修改的文件列表。我使用java watcher服务编写了watcher程序。 但是,如果文件是由eclipse编辑的,则服务不会收到任何通知。

以下是我正在使用的代码:

public class AutoFormatter {

    private static final Integer TAB_TO_SPACE = 4;

    public static void main(String... args) throws IOException, InterruptedException {
        WatchService watcher = FileSystems.getDefault().newWatchService();

        if (Objects.isNull(args) || args.length < 2) {
            printUsage();
        }

        String pathToWatch = args[0];
        String extensionToWatch = args[1];
        System.out.println("Watching path : " + pathToWatch + " for " + extensionToWatch + " files");

        Path watchPath = Paths.get(pathToWatch);

        try {
            watchPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                    StandardWatchEventKinds.ENTRY_MODIFY);

            while (true) {

                WatchKey modifiedKey = watcher.take();
                for (WatchEvent<?> event : modifiedKey.pollEvents()) {
                    System.out.println("event.kind():" + event.kind());
                    if (event.kind().equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path modifiedPath = ev.context();
                        System.out.println("Caught event : " + modifiedPath.toString());
                        if (modifiedPath.toString().endsWith(extensionToWatch)) {
                            System.out.println("Formatting..." + modifiedPath.toString());
                            Formatter.run(modifiedPath.toFile().getAbsolutePath(), TAB_TO_SPACE);
                            System.out.println("Formatting completed... for " + modifiedPath.toString());
                        }
                    }
                }
                if (!modifiedKey.reset())
                    break;

            }

        } catch (IOException x) {
            System.err.println(x);
        }
    }

    private static void printUsage() {
        System.out.println("java TestWatchService /tmp txt - To watch text files being updated in /tmp file");

    }
}

0 个答案:

没有答案