[英]Get location of file created using WatchService
I am using WatchService to watch a folder and its subfolders for new files created. 我正在使用WatchService来监视文件夹及其子文件夹中创建的新文件。 However when a file is created the WatchService gives the name of the file that is created, not its location.
但是,在创建文件时,WatchService会提供所创建文件的名称,而不是其位置。 Is there a way to get the absolute/relative path of the file that was created.
有没有一种方法可以获取所创建文件的绝对/相对路径。
A crude way to solve this issue is to search for the filename in all the subfolders and find the one with the latest create date. 解决此问题的一种粗略方法是在所有子文件夹中搜索文件名,然后找到具有最新创建日期的文件名。 Is there a better way to do this?
有一个更好的方法吗?
If you register a WatchService
on dir
directory, when to get full path is simple: 如果在
dir
目录中注册WatchService
,则获取完整路径的时间很简单:
// If the filename is "test" and the directory is "foo",
// the resolved name is "test/foo".
Path path = dir.resolve(filename);
It works, because WatchService
monitors only one directory. 它有效,因为
WatchService
仅监视一个目录。 If you want to monitor subfolders, you have to register new WatchServices
. 如果要监视子文件夹,则必须注册新的
WatchServices
。
Answer to your unformatted comment (This would solve your problem) 回答您未格式化的评论 (这将解决您的问题)
public static void registerRecursive(Path root,WatchService watchService) throws IOException {
WatchServiceWrapper wsWrapper = new WatchServiceWrapper();
// register all subfolders
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
wsWrapper.register(watchService, dir);
return FileVisitResult.CONTINUE;
}
});
wsWrapper.processEvents();
}
public class WatchServiceWrapper {
private final Map<WatchKey,Path> keys;
public WatchServiceWrapper () {
keys = new HashMap<>();
}
public void register(WatchService watcher, Path dir) throws IOException {
WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
keys.put(key, dir);
}
public void processEvents() {
for (;;) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
//get fileName from WatchEvent ev (code emitted)
Path fileName = ev.context();
Path fullFilePath = dir.resolve(fileName);
//do some other stuff
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.