Java使用WatchService时如何获取文件名?
package org.nhooo.example.io;
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class WatchServiceGetFilename {
public static void main(String[] args) {
try {
//创建一个WatchService并将logDir路径注册到
//观看ENTRY_CREATE的服务。
WatchService watcher = FileSystems.getDefault().newWatchService();
Path logDir = Paths.get("/Users/nhooo/temp");
logDir.register(watcher, ENTRY_CREATE);
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException e) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_CREATE) {
//获取创建文件的名称。
WatchEvent<Path> ev = cast(event);
Path filename = ev.context();
System.out.printf("A new file %s was created.%n",
filename.getFileName());
}
}
key.reset();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
}
热门推荐
10 新年祝福语大全 简短情侣
11 升学宴同学祝福语简短
12 圣诞祝福语简短给师姐
13 新年简短祝福语给亲人
14 保洁阿姨送来祝福语简短
15 朋友祝福语卡片简短大气
16 对部门师姐祝福语简短
17 发文章祝福语简短英语
18 关于水的简短祝福语