java 文件尾部,Java文件尾部实现

implement a java file watcher which is equivalent to tail -f somefile

I've read a few similar questions. and I've seen a few options.

using BufferedReader, basic idea is to use buffered reader to read from the file. if null is returned then sleep a few seconds and then continue in a infinite loop. I experimented a bit on this, my result show as long as you read to the end of the file, then getLine method will no longer give you any updates. so does this approach work at all?

using random access file. every time making a read operation, create a random access file and compare the file length with historical one, if current one is longer, then seek to last read and read in the delta parts. I'm sure this works, but with a new random access file opened each time read, isn't there a more efficient approach ?

I've seen the new JDK added stream API into buffered file reader, I guess this has nothing to do with the new content appended at the tail. it's only related what was first given. my question is could this stream api be extended to take the tailer function into consideration ?

Questions:

can BufferedReader be used to implement tail -f ? in my case, once I read pass EOF, only null is returned.

can JDK8 stream be used to implement tail -f?

is there more efficient implementation other than repeatedly open close file like apache common lib?

解决方案

I eventually used some Apache library to fix this. (will update once I remember it).

essentially the file watchers are file system API dependent. on linux distributions, read over EOF would probably be fine and bring new contents that appended later.

the issue I observed is on MACOs, where once you read after EOF that file handler is no longer valid. you have to reopen the file if you know you are reading new content.

this was on MacOs Maveriks and I didn't test it's still the same on latest versions.

also this was based on the JDK api, not underlying MACOS file system API. because I felt less /F tail -f should have been implemented more efficiently.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值