• JAVA 实现 UNIX tail -f 命令功能


    概述

    如果需要监视附加到文件末尾的行,通常使用带有“ -f ”参数的 UNIX 实用程序“ tail ”来实现。这是一个例子:

    tail -f /var/log/auth.log
    

    如果不仅需要监控附加到文件末尾的新行,还需要在您的应用程序中处理它们怎么办?幸运的是,有一些易于使用的解决方案,本文将介绍其中之一。 Apache Commons IO 提供了解决上述问题的功能。

    依赖项

    首先,必须添加相应的依赖项:

    1. <dependency>
    2. <groupId>commons-iogroupId>
    3. <artifactId>commons-ioartifactId>
    4. <version>2.5version>
    5. dependency>

    应用

    让我们创建一个应用程序来处理附加到文件末尾的行。

    1. import java.io.File;
    2. import org.apache.commons.io.input.Tailer;
    3. import org.apache.commons.io.input.TailerListenerAdapter;
    4. public class TailerApp {
    5. private static class NewLineListener extends TailerListenerAdapter {
    6. @Override
    7. public void handle(String line) {
    8. System.out.println(line);
    9. }
    10. }
    11. private final File file;
    12. private final long delay;
    13. private final TailerListenerAdapter newLineHandler;
    14. public TailerApp(File file, long delay, TailerListenerAdapter newLineHandler) {
    15. this.file = file;
    16. this.delay = delay;
    17. this.newLineHandler = newLineHandler;
    18. }
    19. public void run() {
    20. Tailer tailer = new Tailer(file, newLineHandler, delay);
    21. tailer.run();
    22. }
    23. public static void main(String[] args) {
    24. TailerApp tailer = new TailerApp(new File("C:\\inetpub\\logs\\LogFiles\\W3SVC1\\u_ex220730.log"), 500, new NewLineListener());
    25. tailer.run();
    26. }
    27. }


    必须指定三个参数:

    • 监控文件
    • 延迟(检查文件更改的频率)
    • 回调以处理新行

    要测试应用程序,让我们运行它并在同一文件夹中执行以下命令:

    1. echo -e "test1" >> test.txt
    2. echo -e "test2" >> test.txt
    3. echo -e "test3" >> test.txt

    这些命令将行附加到名为“test.txt”的文件的末尾,我们希望看到它们被我们的应用程序处理。

    让我们看一下应用程序的输出:

    1. test1
    2. test2
    3. test3

    因此,应用程序已成功检测到文件中的新行并对其进行处理

  • 相关阅读:
    git-使用命令笔记
    [附源码]Python计算机毕业设计Django勤工助学管理系统
    008. 子集
    mongodb使用x509认证
    Postgresql 主从复制+主从切换(流复制)
    警告:新版Outlook会向微软发送密码、邮件和其他数据
    ⑱霍兰德ER*如何选专业?高考志愿填报选专业
    Three.js快速入门
    raylib部分源代码功能解读
    深入理解java垃圾回收机制
  • 原文地址:https://blog.csdn.net/allway2/article/details/126068398