如果 Java 中存在触发器(即某些事件,例如新文件添加到目录),我想运行一个任务。 Java 对此有内置支持吗? 如果没有,我可以使用什么第三方库来实现这一点?
最佳答案
在 Java 7 中,有一个监视服务,允许在文件或目录上检测到更改或事件时执行任务。
教程:http://docs.oracle.com/javase/tutorial/essential/io/notification.html#overview
API文档:http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html
这是我编写的一个简单示例:
package watcher;
import java.io.IOException;
import java.nio.file.FileSystem;
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 Watcher {
private final FileCreatedAction action;
private final String pathToWatchString;
public Watcher(FileCreatedAction action, String pathToWatchString) {
this.action = action;
this.pathToWatchString = pathToWatchString;
}
public void start() throws IOException {
FileSystem defaultFileSystem = FileSystems.getDefault();
WatchService watchService = defaultFileSystem.newWatchService();
Path pathToWatch = defaultFileSystem.getPath(pathToWatchString);
pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
while(true) {
try {
WatchKey key = watchService.take();
if (key != null) {
for (WatchEvent<?> event: key.pollEvents()) {
if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE))
{
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
Path fullFilename = pathToWatch.resolve(filename);
action.performAction(fullFilename);
}
}
}
} catch (InterruptedException error) {
return;
}
}
}
public static void main(String[] args) throws IOException {
FileCreatedAction action = new FileCreatedAction() {
@Override
public void performAction(Path fullPath) {
System.out.printf("Found file %s", fullPath);
}
};
Watcher watcher = new Watcher(action, "/foo");
watcher.start();
}
}
interface FileCreatedAction {
void performAction(Path fullPath);
}
关于java - 基于触发器java运行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21546878/