java中怎么实时监控文件行尾内容
创始人
2024-12-25 04:41:47
0次

1.WatchService

首先介绍一下WatchService类,WatchService可以监控某一个目录下的文件的变动(新增,修改,删除)并以事件的形式通知文件的变更,这里我们可以实时的获取到文件的修改事件,然后计算出追加的内容,Talk is cheap,Show me the code.

Listener

简单的接口,只有一个fire方法,当事件发生时处理事件。

public interface Listener {  /**   * 发生文件变动事件时的处理逻辑   *    * @param event   */  void fire(FileChangeEvent event);}

FileChangeListener

Listener接口的实现类,处理文件变更事件。

public class FileChangeListener implements Listener {  /**   * 保存路径跟文件包装类的映射   */  private final Map map = new ConcurrentHashMap<>();  public void fire(FileChangeEvent event) {    switch (event.getKind().name()) {    case "ENTRY_MODIFY":      // 文件修改事件      modify(event.getPath());      break;    default:      throw new UnsupportedOperationException(          String.format("The kind [%s] is unsupport.", event.getKind().name()));    }  }  private void modify(Path path) {    // 根据全路径获取包装类对象    FileWrapper wrapper = map.get(path.toString());    if (wrapper == null) {      wrapper = new FileWrapper(path.toFile());      map.put(path.toString(), wrapper);    }    try {      // 读取追加的内容      new ContentReader(wrapper).read();    } catch (IOException e) {      e.printStackTrace();    }  }}

FileWrapper

文件包装类,包含文件和当前读取的行号

public class FileWrapper {  /**   * 当前文件读取的行数   */  private int currentLine;  /**   * 监听的文件   */  private final File file;  public FileWrapper(File file) {    this(file, 0);  }  public FileWrapper(File file, int currentLine) {    this.file = file;    this.currentLine = currentLine;  }  public int getCurrentLine() {    return currentLine;  }  public void setCurrentLine(int currentLine) {    this.currentLine = currentLine;  }  public File getFile() {    return file;  }}

FileChangeEvent

文件变更事件

public class FileChangeEvent {  /**   * 文件全路径   */  private final Path path;  /**   * 事件类型   */  private final WatchEvent.Kind kind;  public FileChangeEvent(Path path, Kind kind) {    this.path = path;    this.kind = kind;  }  public Path getPath() {    return this.path;  }  public WatchEvent.Kind getKind() {    return this.kind;  }}

ContentReader

内容读取类

public class ContentReader {  private final FileWrapper wrapper;  public ContentReader(FileWrapper wrapper) {    this.wrapper = wrapper;  }  public void read() throws FileNotFoundException, IOException {    try (LineNumberReader lineReader = new LineNumberReader(new FileReader(wrapper.getFile()))) {      List contents = lineReader.lines().collect(Collectors.toList());      if (contents.size() > wrapper.getCurrentLine()) {        for (int i = wrapper.getCurrentLine(); i < contents.size(); i++) {          // 这里只是简单打印出新加的内容到控制台          System.out.println(contents.get(i));        }      }      // 保存当前读取到的行数      wrapper.setCurrentLine(contents.size());    }  }}

DirectoryTargetMonitor

目录监视器,监控目录下文件的变化

public class DirectoryTargetMonitor {  private WatchService watchService;  private final FileChangeListener listener;  private final Path path;  private volatile boolean start = false;  public DirectoryTargetMonitor(final FileChangeListener listener, final String targetPath) {    this(listener, targetPath, "");  }  public DirectoryTargetMonitor(final FileChangeListener listener, final String targetPath, final String... morePaths) {    this.listener = listener;    this.path = Paths.get(targetPath, morePaths);  }  public void startMonitor() throws IOException {    this.watchService = FileSystems.getDefault().newWatchService();    // 注册变更事件到WatchService    this.path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);    this.start = true;    while (start) {      WatchKey watchKey = null;      try {        // 阻塞直到有事件发生        watchKey = watchService.take();        watchKey.pollEvents().forEach(event -> {          WatchEvent.Kind kind = event.kind();          Path path = (Path) event.context();          Path child = this.path.resolve(path);          listener.fire(new FileChangeEvent(child, kind));        });      } catch (Exception e) {        this.start = false;      } finally {        if (watchKey != null) {          watchKey.reset();        }      }    }  }  public void stopMonitor() throws IOException {    System.out.printf("The directory [%s] monitor will be stop ...\n", path);    Thread.currentThread().interrupt();    this.start = false;    this.watchService.close();    System.out.printf("The directory [%s] monitor will be stop done.\n", path);  }}

测试类

在D盘新建一个monitor文件夹, 新建一个test.txt文件,然后启动程序,程序启动完成后,我们尝试往test.txt添加内容然后保存,控制台会实时的输出我们追加的内容,PS:追加的内容要以新起一行的形式追加,如果只是在原来的尾行追加,本程序不会输出到控制台,有兴趣的同学可以扩展一下

public static void main(String[] args) throws IOException {    DirectoryTargetMonitor monitor = new DirectoryTargetMonitor(new FileChangeListener(), "D:\\monitor");    monitor.startMonitor();  }

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...