java中如何使用WatchService获取文件名呢?
下文讲述在检测目录变化时,获取文件名的方法分享,如下所示:
实现思路: 获取WatchEvent的context 即可获取filename例:
package com.java265; 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 watcher = FileSystems.getDefault().newWatchService(); Path logDir = Paths.get("D:/Test"); 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) { // Get the name of created file. 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; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。