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.