• 介绍标签:java,nio,WatchService,file,Path,import From: https://blog.51cto.com/suren/5763995
用Java对文件夹做监控的话该怎么办呢?C++的话可以调用本地的库,我们搞Java的当然也可以通过JNI来实现。现在要介绍的是WatchService——从JDK1.7开始有。
• 类图
[caption id="attachment_3386" align="aligncenter" width="798"] java.nio.file的类图[/caption]
• 例子
[codesyntax lang="java"]
package test;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
/**
* Java文件夹监控测试
* @author surenpi.com
* @since jdk1.6
* 2016年1月18日
*/
public class Test
{
public static void main(String[] args) throws Exception
{
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("d:/abctest");
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
boolean change = true;
while(change)
{
WatchKey wk = watchService.take();
for(WatchEvent<?> event : wk.pollEvents())
{
Path changed = (Path) event.context();
System.out.println(changed + "===" + event.count());
}
System.out.println(wk.reset());
}
}
}
[/codesyntax]
• 问题
覆盖一个文件后,会有多个事件触发