0

我正在尝试来自Pro Java 7 NIO.2 第 118 页的小程序

代码是:

class WatchRafaelNadal {
    public void watchRNDir(Path path) throws IOException, InterruptedException {
        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
           path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

                //start an infinite loop
                while (true) {
                //retrieve and remove the next watch key
                final WatchKey key = watchService.take();
                //get list of pending events for the watch key
                for (WatchEvent<?> watchEvent : key.pollEvents()) {

                //get the kind of event (create, modify, delete)
                final Kind<?> kind = watchEvent.kind();
                //handle OVERFLOW event
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                continue;
                }
                //get the filename for the event
                final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                final Path filename = watchEventPath.context();
                //print it out
                System.out.println(kind + " -> " + filename);
                }
                //reset the key
                boolean valid = key.reset();
                //exit loop if the key is not valid (if the directory was deleted, for example)
                if (!valid) {
                break;
                }
           }
       }
    }
}

public class Main {
     public static void main(String[] args) {
        final Path path = Paths.get("C:/Java");
            WatchRafaelNadal watch = new WatchRafaelNadal();
            try {
            watch.watchRNDir(path);
            } catch (IOException | InterruptedException ex) {
            System.err.println(ex);
            }
        }
}

但是,当我更改global.properties文件夹中存在的(或任何文件)中的一行时,C:\\Java我得到的输出为 -

 ENTRY_MODIFY  -> global.properties
 ENTRY_MODIFY  -> global.properties

为什么会引发 2 次事件?
Java中是否有任何服务可以检测文件中精确修改的行/行?

JDK:jdk1.7.0_09
IDE:Eclipse Java EE IDE 版本:Juno 发布
平台:Windows 7

4

1 回答 1

3

你是怎么改文件的?

也许您在技术上更改了文件两次

例如,首先更改内容,然后更新文件元数据,这会产生两个事件。

如果您以能够处理此类情况的方式实现您的应用程序,那可能是最好的。

于 2012-12-22T11:22:30.727 回答