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

查看:207
本文介绍了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
    }
}

我会假设你想把这种类型的功能放在自己的线程中,这样你就可以睡觉了,不会影响你应用程序的其他任何部分。您将要在一个设置器中显示 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天全站免登陆