gpt4 book ai didi

java - 如何实现文件监视程序来监视多个目录

转载 作者:行者123 更新时间:2023-11-30 07:47:02 25 4
gpt4 key购买 nike

我需要监视多个文件夹以获取新文件通知。我尝试过单个目录,它工作正常。
我的文件夹结构如下所示
路径path = Paths.get("c:\users\Test"); 路径path1 = Paths.get("c:\users\test1"); 路径path2 = Paths.get("c:\users\test2");

public static void watchOutBoundDirectory(Path path) {
String newFile = null;
try {
Boolean isFolder = (Boolean) Files.getAttribute(path, "basic:isDirectory", NOFOLLOW_LINKS);
if (!isFolder) {
throw new IllegalArgumentException("Path: " + path + " is not a folder");
}
} catch (IOException ioe) {
// Folder does not exists
ioe.printStackTrace();
}
// We obtain the file system of the Path
FileSystem fs = path.getFileSystem();
try (WatchService service = fs.newWatchService()) {
path.register(service, ENTRY_CREATE);
WatchKey key = null;
while (true) {
key = service.take();
Kind<?> kind = null;
for (WatchEvent<?> watchEvent : key.pollEvents()) {
kind = watchEvent.kind();
if (OVERFLOW == kind) {
continue;
} else if (ENTRY_CREATE == kind) {
Path newPath = ((WatchEvent<Path>) watchEvent).context();
Path fullPath = path.resolve(newPath);
String newFile = fullPath.toString();
}
}

if (!key.reset()) {
break; // loop
}
}

} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}

}

我尝试将每个目录注册到观察者。WatchKey key1 = path1.register(watcher, ENTRY_CREATE);WatchKey key2 = path2.register(watcher, ENTRY_CREATE);我想在程序启动时监视多个文件夹中的传入事件。并行监视文件夹,直到我停止程序。如何实现?

提前致谢。请帮忙请帮忙

最佳答案

while (true) {
....
}

由于您有一个无限循环,一旦您调用 watchOutBoundDirectory 静态函数。除非您禁用观察者,否则它永远不会逃脱范围。

因此,要么对每个路径使用多线程,要么将路径数组传递给 watchOutBoundDirectory 并检查 while(true) 范围内的每个路径。

关于java - 如何实现文件监视程序来监视多个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33782037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com