java实现tail,unix / linux“tail -f”的Java IO实现

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

}

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

}

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值