jdk 1.7 监听文件目录

本文介绍了一个使用Java NIO的文件系统监听示例程序,该程序可以监控指定目录下的文件创建、删除及修改事件,并实时打印出发生的事件类型及文件名。
 package com;


import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;




import static java.nio.file.StandardWatchEventKinds.*;
public class Test {
    WatchService watch;
    
    public Test(Path path) throws IOException {
    watch = FileSystems.getDefault().newWatchService();
    path.register(watch,ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
    }

    public void handleEvents() throws InterruptedException{
        while(true){
            WatchKey key = watch.take();
            for(WatchEvent event : key.pollEvents()){
                WatchEvent.Kind kind = event.kind();


                if(kind == OVERFLOW){//事件可能lost or discarded
                    continue;
                }


                WatchEvent e = (WatchEvent)event;
                Path fileName = (Path) e.context();


                System.out.printf("Event %s has happened,which fileName is %s%n"
                        ,kind.name(),fileName);

            }

           //如果事件invail

            if(!key.reset()){
                break;
            }
        }
    }
    
    public static void main(String[] args) {
try {
new Test(Paths.get("F://")).handleEvents();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值