【发布时间】:2021-03-04 06:13:31
【问题描述】:
我正在使用java.nio.file.WatchService 观看目录;
每次创建文件时,我都会调用 processFile() 并传递文件句柄。
这是观察者的代码:
boolean poll = true;
System.out.println("Watching Directory: "+path.toString()+"...");
while (poll) {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent<Path> ev = cast(event);
Path dir = (Path)key.watchable();
Path fullPath = dir.resolve(ev.context());
File file = new File(fullPath.toString());
System.out.println("Event kind:" + event.kind()
+ ". File affected: " + event.context()
+ ". Full path" + fullPath);
if(event.kind() == ENTRY_CREATE) fileProcessor.processFile(file);
}
poll = key.reset();
}
这里是 processFile() 代码:
public void processFile(File file) {
String threadName = "Thread-" + file.getName();
Thread t = ProcessorUtil.getThreadByName(threadName);
if (t == null || !t.isAlive()) {
new Thread(() -> {
try {
Thread.sleep(1000); //HACKY WAY of WAITING
InputStream in = new FileInputStream(file);
someProcess(in);
} catch (Exception e) {
_log.error("Exception: ",e);
}
}, threadName).start();
} else {
System.out.println("File "+file.getName()+" currently being processes");
}
如您所见,我正在等待系统写入文件,然后才能访问FileInputStream。这对我来说似乎不对,我想知道是否有比调用Thread.sleep() 更好的方法。
【问题讨论】:
标签: java multithreading file-watcher watchservice