zoukankan      html  css  js  c++  java
  • java监控文件夹的动态

    package com.fenye.puil.usbDemo;


    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 UsbDemo {
    public static void main(String[] args) {
    //初始化被监控的文件夹
    //U盘插入会在此目录上显示所以监控,所以实时监控此文件夹就行
    final Path path = Paths.get("D://Usb");
    //创建WatchService实例,WatchService类似于观察者模式中的观察者
    try (WatchService service = FileSystems.getDefault().newWatchService()) {
    //将path注册到WatchService中
    path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_MODIFY,
    StandardWatchEventKinds.ENTRY_DELETE);
    while (true) {
    //注册监听服务,获取事件的各个属性
    //serviec.take()这个方法会一直堵塞,直到某个事件发生。
    WatchKey key = service.take();
    for (WatchEvent<?> watchEvent : key.pollEvents()) {
    final WatchEvent.Kind<?> kind = watchEvent.kind();
    //丢失或放弃事件时被触发
    if (kind == StandardWatchEventKinds.OVERFLOW) {
    continue;
    }
    //当新的文件夹或者文件出现时
    else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
    //final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
    //final Path filename = watchEventPath.context();
    // print it out
    System.out.println("U盘 :" + " 已插入");
    }
    //当有任意文件被修改时
    else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
    System.out.println("========文件被修改========");
    }
    //当文件夹或者文件消失时
    else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
    //final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
    //final Path filename = watchEventPath.context();
    // print it out
    System.out.println("U盘 :" + " 已拔出");

    }
    }
    //WatchKey实例通过poll或者take返回后,就不会捕获任何事件
    //调用reset()方法就可以将这个WatchKey重新回到watchservice队列,可以重新等待新的事件。
    boolean valid = key.reset();
    if (!valid) {
    break;
    }
    }
    } catch (Exception e) {
    System.err.println(e);
    }
    }
    }





  • 相关阅读:
    解决silverlight中“跨线程访问无效”错误
    VS 制作自定义安装程序
    SQL Server 2005开窗函数的使用
    主要邮件服务器地址
    sql数据库的备份还原操作出现的常见问题
    先安装ArcGIS9.3 后VS2008 出现的问题
    无法启动调试 未安装silverlight developer 运行时 解决办法
    SQL中ROW_NUMBER()的使用
    运用PMI主义
    Understanding the error message: “Login failed for user ''. The user is not associated with a trusted SQL Server connect
  • 原文地址:https://www.cnblogs.com/maocai2018/p/9933420.html
Copyright © 2011-2022 走看看