Java如何實現文件變動的監聽.md

在Java 7發佈的新的IO框架中,除了大家都熟知的 FileVisitor 接口外,還有個 WatchService 接口經常被人忽視掉。 這個類可以讓你實時的監控操作系統中文件的變化,包括創建、更新和刪除事件。

WatchService 用來觀察被註冊了的對象的變化和事件。它和Watchable兩個接口的配合使用, WatchService類似於在觀察者模式中的觀察者,Watchable類似域觀察者模式中的被觀察者。

而Java 7中的java.nio.file.Path類就實現了Watchable接口,這樣的話,和Path類一起可實現觀察者模式。

package com.huawei.leetcode;

import java.io.File;
import java.io.IOException;
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;
import java.util.List;

/**
 * TODO Class Description
 * @since 2019-11-20
 */
public class DirectoryWatcherExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();

        //需要監聽的文件目錄(只能監聽目錄)
        Path path = Paths.get("D:\\code\\my_exercise_code\\src\\com\\xx\\leetcode");
        path.register(watchService,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_CREATE);

        Thread thread = new Thread(() -> {
            try {
                while (true) {
                    WatchKey watchKey = watchService.take();
                    List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
                    for (WatchEvent<?> event : watchEvents) {
                        Path fileName = (Path) event.context();
                        System.out.println("文件更新: " + fileName);
                        System.out.println("FileName: " + fileName.getFileName());

                        if (event.context().toString().contains("xx.txt")) {
                            System.out.println(event.context() + "]文件發生了[" + event.kind() + "]事件");
                        }
                    }
                    watchKey.reset();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();

        System.out.println("-------success-------");
    }
}

參考文獻:使用WatchService監聽文件變化

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章