unix/linux“tail -f"的Java IO实现 [英] Java IO implementation of unix/linux "tail -f"

查看:34
本文介绍了unix/linux“tail -f"的Java IO实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用什么技术和/或库来实现 linux 命令tail -f"的功能.我本质上是在寻找 java.io.FileReader 的附加组件/替代品.客户端代码可能如下所示:

I'm wondering what techniques and/or library to use to implement the functionality of the linux command "tail -f ". I'm essentially looking for a drop in add-on/replacement for java.io.FileReader. Client code could look something like this:

TailFileReader lft = new TailFileReader("application.log");
BufferedReader br = new BufferedReader(lft);
String line;
try {
  while (true) {
    line= br.readLine();
    // do something interesting with line
  }
} catch (IOException e) {
  // barf
}

缺少的部分是 TailFileReader 的合理实现.它应该能够读取文件打开之前存在的文件部分以及添加的行.

The missing piece is a reasonable implementation of TailFileReader. It should be able to read parts of the file that exist before the file is opened as well as the lines that are added.

推荐答案

继续读取文件并等待文件有更多更新的能力应该不难自己在代码中完成.这是一些伪代码:

The ability to continue to read a file, and wait around until the file has some more updates for you shouldn't be that hard to accomplish in code yourself. Here's some pseudo-code:

BufferedReader br = new BufferedReader(...);
String line;
while (keepReading) {
    line = reader.readLine();
    if (line == null) {
        //wait until there is more of the file for us to read
        Thread.sleep(1000);
    }
    else {
        //do something interesting with the line
    }
}

我假设您希望将这种类型的功能放在它自己的线程中,这样您就可以休眠它而不会影响应用程序的任何其他区域.您可能希望在 setter 中公开 keepReading 以便您的主类/应用程序的其他部分可以安全地关闭线程而不会出现任何其他麻烦,只需调用 stopReading() 或类似的东西.

I would assume that you would want to put this type of functionality in its own Thread, so that you can sleep it and not affect any other areas of your application. You would want to expose keepReading in a setter so that your main class / other parts of the application can safely shut the thread down without any other headaches, simply by calling stopReading() or something similar.

这篇关于unix/linux“tail -f"的Java IO实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆