0

我知道java.nio.file可以提供方法来观察文件的变化,比如新文件、修改和删除。但现在我想知道是否有一种方法可以查看是否正在输入目录或某个文件是否被某个应用程序(如编辑器)打开。

我已经阅读了 API 文档,但找不到实现这一目标的方法。任何人都可以提供有关此问题的线索,也许是其他 API 文档,而不是java.nio.file可以提供解决此问题的方法。

4

1 回答 1

1

查看http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html

至于您可以观看的内容,请查看http://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardWatchEventKinds.html

它看起来不支持您在其他评论中指出的“正在打开文件”或“有人进入目录”之类的东西。

这是一个简单的观察者的示例:

package com.stackoverflow.answers;

import java.io.IOException;
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 FolderWatcher {
    public static void main(String[] args) throws IOException, InterruptedException {
        WatchService watcher = FileSystems.getDefault().newWatchService();
        Path dir = FileSystems.getDefault().getPath("c:/Temp");
        dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
        // ...

        for (;;) {
            WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.println("Got event: " + event.kind());
                if (event.kind() == StandardWatchEventKinds.OVERFLOW) continue;

                System.out.println("File: " + ((WatchEvent<Path>)event).context());
            }
        }
    }
}

有关更完整的处理,请查看本教程:http ://docs.oracle.com/javase/tutorial/essential/io/notification.html

于 2014-04-15T17:21:45.573 回答