java7 文件监听器

来源:互联网 发布:生日祝福网站源码 编辑:程序博客网 时间:2024/06/05 10:05

java7中的文件监听,主要可以监听指定目录下的文件:新建 删除 修改等操作。StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE 这三个事件 被注册到watchService 对象中,之后就可以监听指定目录下的文件。如下代码所示:


package com.java7filespaths;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.FileSystems;
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 TestFilesPaths {

    public static void main(String[] args) {
    //获取文件系统的WatchService 对象
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            //为指定目录路径注册舰艇
            Paths.get("E:\\").register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE);
            while(true){
                //获取下一个文件变化事件
                try {
                    WatchKey key = watchService.take();
                    for (WatchEvent<?> enent : key.pollEvents()) {
                        System.out.println(enent.context()+"文件发生了"+enent.kind()+"事件");
                    }
                    if(!key.reset()){
                        break;
                    }
                    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
  
        /*//测试Files 工具类copy 方法
        try {
            Files.copy(Paths.get("E://aa.txt"), new FileOutputStream(new File("E://bb.txt")));
            System.out.println("拷贝方法 拷贝完了。。。");
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        
    }

}

0 0
原创粉丝点击