使用Java7提供的WatchService给目录添加新建文件监控

程序:

import java.io.IOException;
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;

public class Java7FolderListener {
    public static void main(String[] a) {
        beginWatchFolder("C:\TEMP");
    }
    
    private static void beginWatchFolder(String folderName) {
        final Path path = Paths.get(folderName);
        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            // 给path路径加上文件观察服务
            path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
            while (true) {
                final WatchKey key = watchService.take();
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    final WatchEvent.Kind<?> kind = watchEvent.kind();

                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("[新建]");
                    }
                    
                    // get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();
                    // print it out
                    System.out.println(kind + " -> " + filename);
                }
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException | InterruptedException ex) {
            System.err.println(ex);
        }
    }
}

输出:

[新建]
ENTRY_CREATE -> LICENSE
[新建]
ENTRY_CREATE -> README.html
[新建]
ENTRY_CREATE -> release

参考:

https://www.cnblogs.com/Soy-technology/p/11779262.html#/cnblog/works/article/11779262

--2020年4月5日--

原文地址:https://www.cnblogs.com/heyang78/p/12635820.html