我有 Java 程序监视安装在本地服务器中的远程文件夹。 但只要远程文件夹中发生更改,它就不会检测到任何更改/修改。
如果在安装的文件夹中进行更改/修改,则工作正常。
通过网络搜索,如 Java 文档中所述
If a watched file is not located on a local storage device then it is implementation specific if changes to the file can be detected. In particular, it is not required that changes to files carried out on remote systems be detected.
任何人都可以帮助我提供有关如何执行此操作的示例吗?下面是我当前的代码
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get(directory);
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (Exception ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
if (kind == ENTRY_MODIFY) {
System.out.println("file has changed");
// other process
}
if (kind == ENTRY_CREATE) {
System.out.println("file has created");
// other process
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
最佳答案
我有同样的问题并使用了 org.apache.commons.io.monitor.FileAlterationMonitor
。
之前帖子中建议的 pom.xml 更改如下
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
对我有用的代码片段如下:
String monitoringDirectory= "<YOUR CODE HERE>";
FileAlterationObserver observer = new FileAlterationObserver(monitorDirectory);
logger.info("Start ACTIVITY, Monitoring "+monitorDirectory);
observer.addListener(new FileAlterationListenerAdaptor(){
@Override
public void onDirectoryCreate(File file) {
logger.info("New Folder Created:"+file.getName());
}
@Override
public void onDirectoryDelete(File file) {
logger.info("Folder Deleted:"+file.getName());
}
@Override
public void onFileCreate(File file) {
logger.info("File Created:"+file.getName()+": YOUR ACTION");
}
@Override
public void onFileDelete(File file) {
logger.info("File Deleted:"+file.getName()+": NO ACTION");
}
});
/* Set to monitor changes for 500 ms */
FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
try {
monitor.start();
} catch (Exception e) {
logger.error("UNABLE TO MONITOR SERVER" + e.getMessage());
e.printStackTrace();
}
关于Java 监视服务 : Not Working for Remote Files mounted in the local Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48919086/