java如何在linux下监听某个目录下是否有文件改变?
java如何在linux下监听某个目录下是否有文件改变?比如说在Home\www\下存在了一个新的文件,java就会立即监听到,然后进行读取的操作呢?linuxtomca...
java如何在linux下监听某个目录下是否有文件改变?比如说在Home\www\下存在了一个新的文件,java就会立即监听到,然后进行读取的操作呢?linux tomcat
展开
3个回答
展开全部
JDK 7 的nio2 WatchService可以监听文件系统。
Oracle官方教程链接 http://docs.oracle.com/javase/tutorial/essential/io/notification.html
样例代码:
import static java.nio.file.StandardWatchEventKinds.*;
Path path = Paths.get("/home");
WatchService watchService = FileSystems.getDefault().newWatchService();
WatchKey watchKey = path.register(watchService,ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
/*
private boolean notDone = true;
while(notDone){
try{
WatchKey watchKey = watchService.poll(60,TimeUnit.SECONDS);
List<WatchEvent.Kind<?>> events = watchKey.pollEvents();
for(WatchEvent event : events){
//WatchKey watchable returns the calling Path object of Path.register
Path watchedPath = (Path) watchKey.watchable();
//returns the event type
StandardWatchEventKinds eventKind = event.kind();
//returns the context of the event
Path target = (Path)event.context();
}
if(!watchKey.reset()){
...handle situation no longer valid
}
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询