public static void main (String args[]) throws Exception {
Path _directotyToWatch = Paths.get(args[0]);
WatchService watcherSvc = FileSystems.getDefault().newWatchService();
WatchKey watchKey = _directotyToWatch.register(watcherSvc, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
while (true) {
watchKey=watcherSvc.take();
for (WatchEvent<?> event: watchKey.pollEvents()) {
WatchEvent<Path> watchEvent = castEvent(event);
System.out.println(event.kind().name().toString() + " " + _directotyToWatch.resolve(watchEvent.context()));
watchKey.reset();
}
}
}
在上例中,watch目錄路徑取自控制檯參數。 我想靜態傳遞目錄路徑。WatchService watch創建文件的specfic目錄
嘗試此Paths.get(「O:\\ test」);但拋出異常
Exception in thread "main" java.lang.NoClassDefFoundError: java/nio/file/Paths
at JSR203_NIO2_WatchFolder.main(JSR203_NIO2_WatchFolder.java:40)
Caused by: java.lang.ClassNotFoundException: java.nio.file.Paths
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
'Paths.get( 「O:\測試」) ;「我懷疑會編譯 - '非法轉義字符'。 – 2012-01-12 05:31:17
其\t \t Paths.get(「O:\\ test」) – Sushant 2012-01-12 06:37:47
'java -version'的輸出是什麼? – 2012-01-12 07:27:45