I want to read the last n lines of a very big file without reading the whole file into any buffer/memory area using Java.
I looked around the JDK APIs and Apache Commons I/O and am not able to locate one which is suitable for this purpose.
I was thinking of the way tail or less does it in UNIX. I don't think they load the entire file and then show the last few lines of the file. There should be similar way to do the same in Java too.
CircularFifoBuffer from apache commons . answer from a similar question at How to read last 5 lines of a .txt file into java
Note that in Apache Commons Collections 4 this class seems to have been renamed to CircularFifoQueue
Here is the working for this.
I found
RandomAccessFile
and other Buffer Reader classes too slow for me. Nothing can be faster than atail -<#lines>
. So this it was the best solution for me.I found it the simplest way to do by using
ReversedLinesFileReader
from apache commons-io api. This method will give you the line from bottom to top of a file and you can specifyn_lines
value to specify the number of line.