集册 Java实例教程 监视目录中的内容更改

监视目录中的内容更改

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

584
使用WatchService可以订阅有关文件夹中发生的事件的通知。

import java.io.IOException;

import java.nio.file.FileSystem;

import java.nio.file.FileSystems;

import java.nio.file.Path;/** 来自 N o w  J a v a  .   c o m**/

import java.nio.file.StandardWatchEventKinds;

import java.nio.file.WatchEvent;

import java.nio.file.WatchKey;

import java.nio.file.WatchService;

import java.util.concurrent.TimeUnit;


public class Main {

  public static void main(String[] args) {

    try {

      System.out.println("Watch Event, press q<Enter> to exit");

      FileSystem fileSystem = FileSystems.getDefault();

      WatchService service = fileSystem.newWatchService();

      Path path = fileSystem.getPath(".");

      System.out.println("Watching :" + path.toAbsolutePath());/** from 时代Java公众号 - N o w J a  v a . c o m**/

      path.register(service, StandardWatchEventKinds.ENTRY_CREATE,

          StandardWatchEventKinds.ENTRY_DELETE,

          StandardWatchEventKinds.ENTRY_MODIFY);

      boolean shouldContinue = true;

      while (shouldContinue) {

        WatchKey key = service.poll(250, TimeUnit.MILLISECONDS);

        while (System.in.available() > 0) {

          int readChar = System.in.read();

          if ((readChar == 'q') || (readChar == 'Q')) {

            shouldContinue = false;

            break;

          }

        }

        if (key == null)

          continue;

        key.pollEvents()

            .stream()

            .filter(

                (event) -> !(event.kind() == StandardWatchEventKinds.OVERFLOW))

            .map((event) -> (WatchEvent<Path>) event)

            .forEach(

                (ev) -> {

                  Path filename = ev.context();

                  System.out.printl
展开阅读全文