我有一个 java 项目,其组件之一是监视安装到我的计算机上的特定文件夹。
我的linux版本是OpenSUSE 42.1
为了监视我正在使用java的Watch Service的文件夹.
附件是我们在网上找到的文件夹监控的主要代码,并根据需要进行了修改。
(抱歉,没有版权,找不到它的来源)。
构造函数:
/**
* Creates a WatchService and registers the given directory
*/
public WatchDir(Path dir, Kind<?>... dirWatchKinds) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey,Path>();
register(dir, dirWatchKinds);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
watcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
运行方法(实现为可运行):
/**
* Process all events for keys queued to the watcher
*/
public void run() {
while (shouldRun) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (Exception x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
log.error("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
handleDirEvent(child, ev.kind());
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
// Check that dir path still exists. If not, notify user and whoever run the thread
if (Files.notExists(dir)){
//log.error(String.format("Directory ", arg1));
fireFileChangedEvent(dir.getFileName().toString(), FileState.Deleted);
}
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
现在解决我的问题。
已安装的文件夹很容易断开连接,这可能会在我的程序范围之外处理(我猜是从终端)。
目前,当发生这种情况时,watcher.take()
会收到通知,无需处理任何事件,
在 boolean valid = key.reset()
上,它得到值 false,最终导致线程终止。
从那时起,我真的不知道何时会再次安装该文件夹 - 以重新运行监视器线程。
监视文件夹安装/卸载的最佳方法是什么?
请注意:受监控的端点文件夹不一定是安装点,它(安装的文件夹)可能是其祖先之一。
如有任何帮助,我们将不胜感激!
最佳答案
您可以查看/proc/mounts
文件来查看挂载是否仍然存在。
不确定 OpenSUSE,但我认为它们的工作方式与 Redhat 风格的 Linux 相同。 https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s2-proc-mounts.html
关于Java catch linux挂载/卸载文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45035125/