集册 Java实例教程 使用WatchEvents监视文件事件

使用WatchEvents监视文件事件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

463
使用WatchEvents监视文件事件

import java.io.IOException;

import java.nio.file.FileSystem;

import java.nio.file.FileSystems;/** 来自 时代Java公众号 - nowjava.com**/

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 Main {


    public static void main(String[] args) {

        try {

            FileSystem fileSystem = FileSystems.getDefault();

            WatchService watchService = fileSystem.newWatchService();

            Path directory = Paths.get("/home/docs");//来自 n o w j a v a . c o m - 时  代  Java

            WatchEvent.Kind<?>[] events = {

                StandardWatchEventKinds.ENTRY_CREATE,

                StandardWatchEventKinds.ENTRY_DELETE,

                StandardWatchEventKinds.ENTRY_MODIFY};

            directory.register(watchService, events);

            while (true) {

                System.out.println("Waiting for a watch event");

                WatchKey watchKey = watchService.take();


                System.out.println("Path being watched: " + watchKey.watchable());

                System.out.println();


                if (watchKey.isValid()) {

                    for (WatchEvent<?> event : watchKey.pollEvents()) {

                        System.out.println("Kind: " + event.kind());

                        System.out.println("Context: " + event.context());

                        System.out.println("Count: " + event.count());

                        System.out.println();

                    }


                    boolean valid = watchKey.reset();

展开阅读全文