Java实现文件夹的监控

一、实现单级文件夹的监听(只监听该文件夹下的变化)

    public static void main(String[] args) {
        final Path path = Paths.get("D:\\test");
        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.OVERFLOW) {
                        continue;
                    }
                    //创建事件
                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("[新建]");
                    }
                    //修改事件
                    if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("修改]");
                    }
                    //删除事件
                    if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        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);
        }
    }

自定义监听模式:

public static boolean watchDirectory(String dirPath) {
        // 判断要监控的目录是否存在
        if (!(new File(dirPath).exists())) {
            System.out.println(MessageFormat.format("目录{0}不存在!", dirPath));
            return false;
        }
        // 注册要监控的文件夹
        Path watchDirectory = Paths.get(new File(dirPath).getPath());
        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            watchDirectory.register(watchService,
                    // 指定要监控的文件操作类型,创建/修改/删除
                    StandardWatchEventKinds.ENTRY_CREATE);
//            watchDirectory.register(watchService,StandardWatchEventKinds.ENTRY_MODIFY);
//            watchDirectory.register(watchService,StandardWatchEventKinds.ENTRY_DELETE);
            // 死循环执行监控
            while (true) {
                // 获取文件操作对象
                WatchKey watchKey = watchService.take();
                // 针对不同的文件操作类型进行处理
                for (WatchEvent event : watchKey.pollEvents()) {
                    WatchEvent.Kind eventKind = event.kind();
                    if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }
                    // 获取发生改变的文件名
                    String fileName = event.context().toString();
                    // 当文件创建执行
                    if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println(fileName);
                        String path=dirPath+"/"+fileName;
                        System.out.println(path);
                        if (new File(path).isDirectory()){
                            System.out.println("文件夹");
                        }else {
                            System.out.println("文件");
                        }
                    }

                }
                // 每次执行完后重置
                boolean isKeyValid = watchKey.reset();
                if (!isKeyValid) {
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return true;
    }

二、实现多级文件夹的监听(监听该文件夹及以下文件及文件夹的变化)

public class FileListener extends FileAlterationListenerAdaptor {
    private Logger log = Logger.getLogger(FileListener.class);

    /**
     * 文件创建执行
     */
    public void onFileCreate(File file) {
        log.info("[新建]:" + file.getAbsolutePath());
    }
    /**
     * 文件创建修改
     */
    public void onFileChange(File file) {
        log.info("[修改]:" + file.getAbsolutePath());
    }
    /**
     * 文件删除
     */
    public void onFileDelete(File file) {
        log.info("[删除]:" + file.getAbsolutePath());
    }
    /**
     * 目录创建
     */
    public void onDirectoryCreate(File directory) {
        log.info("[新建]:" + directory.getAbsolutePath());
    }
    /**
     * 目录修改
     */
    public void onDirectoryChange(File directory) {
        log.info("[修改]:" + directory.getAbsolutePath());
    }
    /**
     * 目录删除
     */
    public void onDirectoryDelete(File directory) {
        log.info("[删除]:" + directory.getAbsolutePath());
    }
    public void onStart(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStart(observer);
    }
    public void onStop(FileAlterationObserver observer) {
        // TODO Auto-generated method stub
        super.onStop(observer);
    }
}
public static void main(String[] args) {
    // 轮询间隔 5 秒
    long interval = TimeUnit.SECONDS.toMillis(5);
    //不使用过滤器,使用过滤器时创建FileAlterationObserver对象时传入第二个参数FileFilter
    FileAlterationObserver observer = new FileAlterationObserver(new File("D:\\test"));
    FileListener fileListener = new FileListener();
    observer.addListener(fileListener);
    //创建文件变化监听器
    FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
    // 开始监控
    try {
        monitor.start();
    }catch (Exception e){}
}

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的WatchService来监控文件夹中新增的文件。WatchService是Java NIO 2中的一个特性,它可以监控文件系统的变化,如文件的创建、修改和删除等。 以下是一个简单的示例代码,用于监控指定文件夹中新增的文件: ```java import java.nio.file.*; public class FolderWatcher { public static void main(String[] args) throws Exception { // 获取文件监控服务 WatchService watchService = FileSystems.getDefault().newWatchService(); // 注册要监控文件夹,并设置监控类型为新增文件 Path folderPath = Paths.get("/path/to/folder"); folderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); // 循环获取文件变化事件 while (true) { WatchKey watchKey = watchService.take(); // 遍历所有文件变化事件 for (WatchEvent<?> event : watchKey.pollEvents()) { // 判断事件类型是否为新增文件 if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { // 获取新增文件的路径 Path filePath = folderPath.resolve((Path) event.context()); System.out.println("New file created: " + filePath); } } // 重置监控,以便下次继续监控 watchKey.reset(); } } } ``` 在上面的示例代码中,我们首先获取了文件监控服务,并注册了要监控文件夹监控类型。然后,我们进入一个无限循环,在循环中不断获取文件变化事件,并判断事件类型是否为新增文件。如果是新增文件,则输出文件的路径。最后,我们重置监控以便下次继续监控

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值