查看目录中的更改Java.nio.file

查看目录中的更改Java.nio.file,java,file,watchservice,Java,File,Watchservice,我知道java.nio.file可以提供监视文件更改的方法,比如新文件、修改和删除。但现在我想知道是否有一种方法可以观察某个应用程序(如编辑器)是否正在输入目录或打开一个文件 我已经阅读了API文档,但找不到实现这一点的方法。有人能提供一些关于这方面的线索吗?也许是其他API文档,而不是java.nio.file,它可以提供解决这一问题的方法。请查看 至于你可以看什么,看看吧 它看起来不支持您在其他评论中指出的“正在打开文件”或“有人进入目录”之类的内容 下面是一个简单观察者的示例: packa

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

我已经阅读了API文档,但找不到实现这一点的方法。有人能提供一些关于这方面的线索吗?也许是其他API文档,而不是
java.nio.file
,它可以提供解决这一问题的方法。

请查看

至于你可以看什么,看看吧

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

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

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());
            }
        }
    }
}
package com.stackoverflow.answers;
导入java.io.IOException;
导入java.nio.file.FileSystems;
导入java.nio.file.Path;
导入java.nio.file.StandardWatchEventTypes;
导入java.nio.file.WatchEvent;
导入java.nio.file.WatchKey;
导入java.nio.file.WatchService;
公共类FolderWatcher{
公共静态void main(字符串[]args)引发IOException、InterruptedException{
WatchService watcher=FileSystems.getDefault().newWatchService();
Path dir=FileSystems.getDefault().getPath(“c:/Temp”);
目录注册(观察者、StandardWatchEventTypes.ENTRY\u修改、StandardWatchEventTypes.ENTRY\u创建、StandardWatchEventTypes.ENTRY\u删除);
// ...
对于(;;){
WatchKey=watcher.take();
for(WatchEvent事件:key.pollEvents()){
System.out.println(“Got事件:+event.kind());
如果(event.kind()==StandardWatchEventKinds.OVERFLOW)继续;
System.out.println(“文件:”+((WatchEvent)event.context());
}
}
}
}

要获得更完整的处理,请查看本教程:

我知道java.nio.file可以提供监视文件更改的方法,如新文件、修改和删除
,如果我没有弄错的话,目录应该与文件非常相似。它只是一个列出其内容的文件。如果您想要递归地使用它,那么知道目录是一个文件可能会有点困难,“递归地”可能是以后要考虑的问题。现在,我只想知道是否有一种方法可以像在目录中输入或打开文件一样观看事件:我已经看过文件了。是的,我找不到任何解决办法。我希望有人能告诉我实现这一目标的其他方法。