Efficient way of handling file pointers in Java? (Using BufferedReader with file pointer)

前端 未结 3 2067
渐次进展
渐次进展 2021-01-01 02:11

I have a log file which gets updated every second. I need to read the log file periodically, and once I do a read, I need to store the file pointer position at the end of t

3条回答
  •  情话喂你
    2021-01-01 02:43

    A couple of ways that should work:

    • open the file using a FileInputStream, skip() the relevant number of bytes, then wrap the BufferedReader around the stream (via an InputStreamReader);
    • open the file (with either FileInputStream or RandomAccessFile), call getChannel() on the stream/RandomAccessFile to get an underlying FileChannel, call position() on the channel, then call Channels.newInputStream() to get an input stream from the channel, which you can pass to InputStreamReader -> BufferedReader.

    I haven't honestly profiled these to see which is better performance-wise, but you should see which works better in your situation.

    The problem with RandomAccessFile is essentially that its readLine() method is very inefficient. If it's convenient for you to read from the RAF and do your own buffering to split the lines, then there's nothing wrong with RAF per se-- just that its readLine() is poorly implemented

提交回复
热议问题