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, thengetLine
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 thetailer function
into consideration ?
Questions:
can
BufferedReader
be used to implementtail -f
? in my case, once I read pass EOF, only null is returned.can JDK8
stream
be used to implementtail -f
?is there more efficient implementation other than repeatedly open close file like apache common lib?