zoukankan      html  css  js  c++  java
  • Java监控文件夹变化

    1. 线程轮询扫描
    优点:纯java实现,完美跨平台。
    缺点:监听文件较多时,需要扫描的量太大;响应不是非常及时,依赖于扫描间隔时间。

    2. 文件钩子
    优点:事件驱动方式,无目录扫描。
    缺点:跟平台相关

    Jnotify开发包是个不错的文件钩子库,使用方式如下:

    public class FieMonitor {

        /**      * @param args      */     public static void main(String[] args)     {         String monitedPath = "E:/templete";         int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;         // 是否监视子目录         boolean watchSubtree = true;         try{         int watchID = JNotify.addWatch(monitedPath, mask, watchSubtree, new Listener());         Thread.sleep(1000000);         boolean res = JNotify.removeWatch(watchID);         if (!res)         {             // invalid         }         }catch(Exception e)         {             e.printStackTrace();         }

        }

        public static class Listener implements JNotifyListener     {         public void fileRenamed(int wd, String rootPath, String oldName, String newName)         {             print("renamed " + rootPath + " : " + oldName + " -> " + newName);         }

            public void fileModified(int wd, String rootPath, String name)         {             print("modified " + rootPath + " : " + name);         }

            public void fileDeleted(int wd, String rootPath, String name)         {             print("deleted " + rootPath + " : " + name);         }

            public void fileCreated(int wd, String rootPath, String name)         {             print("created " + rootPath + " : " + name);         }

            void print(String msg)         {             System.err.println(msg);         }     } }

    额外说明:win下面rename一个文件,产生2个事件 rename和 modify

    这个库还有个缺点:要在java.library.path下加入依赖的dll (jnotify.dll/jnotify_64bit.dll),让本人非常不爽。 跟进源码,发现是用的

  • 相关阅读:
    vue中computed和watch的区别,以及适用场景
    vue中使用过的全局API
    厦门中控
    设置圆角的弧度,保持兼容性
    伪元素::after和::before
    SpringMVC
    mui问题
    错误记录
    Android错误
    Android之界面(布局文件layput)
  • 原文地址:https://www.cnblogs.com/lcuzhanglei/p/2538490.html
Copyright © 2011-2022 走看看