• 使用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日--

  • 相关阅读:
    素数
    超级素数
    SUMMARIZE 6.1
    广度优先搜索与八字码问题
    poj2352
    poj1198
    康托展开
    STL里的内存池实现
    构造函数,C++内存管理,内存泄漏定位
    内联函数,宏定义,内存对齐,类型转换
  • 原文地址:https://www.cnblogs.com/heyang78/p/12635820.html
Copyright © 2020-2023  润新知