I have a text file like
one
two
three
four
five
I need to get the offset of each line in the file. How do I do this in Java?
I have searched through some of the I/O libraries(like BufferedReader and RandomAccessFile) but I'm unable to find a satisfactory answer to this.
Can anyone suggest how to deal with this?
a) Byte offset 0, ie. file start
b) Open the file with something to read binary byte blocks (instead of strings etc.),
read the whole file (in a loop with something like up to 4096 byte each time)
and search the bytes with value
'\n'
in the block, in each loop iteration.The position of each
'\n'
plus the count of previous block * 4096 is another line offset.Another approach would be to count the bytes of each line line this
in this example you would also need to add the size of the newline character \n to size of each line