亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java實時監(jiān)控文件行尾內(nèi)容的實現(xiàn)

 更新時間:2020年02月10日 09:23:09   作者:油頭粉面  
這篇文章主要介紹了java實時監(jiān)控文件行尾內(nèi)容的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

今天講一下怎樣用Java實現(xiàn)實時的監(jiān)控文件行尾的追加內(nèi)容,類似Linux命令

tail -f

在之前的面試中遇到過一個問題,就是用Java實現(xiàn)tail功能,之前的做法是做一個定時任務(wù)每隔1秒去讀取一次文件,去判斷內(nèi)容是否有追加,如果有則輸出新追加的內(nèi)容,這個做法雖然能勉強實現(xiàn)功能,但是有點太low,今天采用另外一種實現(xiàn)方式,基于事件通知。

1.WatchService

首先介紹一下WatchService類,WatchService可以監(jiān)控某一個目錄下的文件的變動(新增,修改,刪除)并以事件的形式通知文件的變更,這里我們可以實時的獲取到文件的修改事件,然后計算出追加的內(nèi)容,Talk is cheap,Show me the code.

Listener

簡單的接口,只有一個fire方法,當(dāng)事件發(fā)生時處理事件。

  public interface Listener {

  /**
   * 發(fā)生文件變動事件時的處理邏輯
   * 
   * @param event
   */
  void fire(FileChangeEvent event);
}

FileChangeListener

Listener接口的實現(xiàn)類,處理文件變更事件。

public class FileChangeListener implements Listener {

  /**
   * 保存路徑跟文件包裝類的映射
   */
  private final Map<String, FileWrapper> 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) {
    // 根據(jù)全路徑獲取包裝類對象
    FileWrapper wrapper = map.get(path.toString());
    if (wrapper == null) {
      wrapper = new FileWrapper(path.toFile());
      map.put(path.toString(), wrapper);
    }
    try {
      // 讀取追加的內(nèi)容
      new ContentReader(wrapper).read();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

FileWrapper

文件包裝類,包含文件和當(dāng)前讀取的行號

public class FileWrapper {

  /**
   * 當(dāng)前文件讀取的行數(shù)
   */
  private int currentLine;

  /**
   * 監(jiān)聽的文件
   */
  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

內(nèi)容讀取類

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<String> contents = lineReader.lines().collect(Collectors.toList());
      if (contents.size() > wrapper.getCurrentLine()) {
        for (int i = wrapper.getCurrentLine(); i < contents.size(); i++) {
          // 這里只是簡單打印出新加的內(nèi)容到控制臺
          System.out.println(contents.get(i));
        }
      }
      // 保存當(dāng)前讀取到的行數(shù)
      wrapper.setCurrentLine(contents.size());
    }
  }

}

DirectoryTargetMonitor

目錄監(jiān)視器,監(jiān)控目錄下文件的變化

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 {
        // 阻塞直到有事件發(fā)生
        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添加內(nèi)容然后保存,控制臺會實時的輸出我們追加的內(nèi)容,PS:追加的內(nèi)容要以新起一行的形式追加,如果只是在原來的尾行追加,本程序不會輸出到控制臺,有興趣的同學(xué)可以擴展一下

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java開發(fā)環(huán)境配置方法

    Java開發(fā)環(huán)境配置方法

    這篇文章主要介紹了并不是每一臺計算機都可以運行Java程序,要運行Java程序,計算機必須學(xué)習(xí)搭建Java開發(fā)環(huán)境,需要的朋友可以參考下
    2015-07-07
  • Java中6種單例模式寫法代碼實例

    Java中6種單例模式寫法代碼實例

    這篇文章主要介紹了Java中6種單例模式寫法代碼實例,某個類任何情況下只有一個實例,并提供一個全局訪問點來獲取該實例,Java6種單例模式有2種懶漢式,2種餓漢式,靜態(tài)內(nèi)部類 ,枚舉類,需要的朋友可以參考下
    2024-01-01
  • Mybatis Generator最完美配置文件詳解(完整版)

    Mybatis Generator最完美配置文件詳解(完整版)

    今天小編給大家整理了一篇關(guān)于Mybatis Generator最完美配置文件詳解教程,非常不錯具有參考借鑒價值,感興趣的朋友一起學(xué)習(xí)吧
    2016-11-11
  • Java中Request請求轉(zhuǎn)發(fā)詳解

    Java中Request請求轉(zhuǎn)發(fā)詳解

    這篇文章主要介紹了Java中Request請求轉(zhuǎn)發(fā)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • iReport使用教程(示例教程)

    iReport使用教程(示例教程)

    在使用ireport的過程中,因為各種功能都要百度,但是大家使用的例子又千差萬別讓人很苦惱,所以用一個簡單例子貫穿的展示一下ireport的常見功能
    2021-10-10
  • spring boot jar部署控制臺日志亂碼的解決

    spring boot jar部署控制臺日志亂碼的解決

    這篇文章主要介紹了spring boot jar部署控制臺日志亂碼的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • MybatisPlus使用排序查詢時將null值放到最后

    MybatisPlus使用排序查詢時將null值放到最后

    按照更新時間排序,但是更新時間可能為null,因此將null的數(shù)據(jù)放到最后,本文主要介紹了MybatisPlus使用排序查詢時將null值放到最后,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • Java詳細(xì)講解包的作用以及修飾符的介紹

    Java詳細(xì)講解包的作用以及修飾符的介紹

    本文主要講述的是包的使用和注意事項和四種訪問修飾符public,protected,默認(rèn)的,private的訪問范圍及實例,感興趣的朋友一起來看看
    2022-05-05
  • 解決idea spring boot 修改html等不重啟即時生效的問題

    解決idea spring boot 修改html等不重啟即時生效的問題

    這篇文章主要介紹了解決idea spring boot 修改html等不重啟即時生效的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • Spring?Boot整合ELK實現(xiàn)日志采集與監(jiān)控

    Spring?Boot整合ELK實現(xiàn)日志采集與監(jiān)控

    這篇文章主要介紹了Spring?Boot整合ELK實現(xiàn)日志采集與監(jiān)控,需要的朋友可以參考下
    2022-06-06

最新評論