• 介紹
用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]
• 問題
覆寫一個檔案後,會有多個事件觸發