Search code examples
javafilenio

How can I jump to specific line and read from that in java


I meet a big file(much GB),and I want to jump to specific line directly, and then read some line from that...

for example, I hava file like

1.aaaaaaaaaaaa
2.bbbbbbbbbbbb
3.cccccccccccc
4.dddddddddddd

and want to read lines from 3 and 4. now doesn't using 'readLine()' for handling 1....2 line, but staring my journey at 3 and read 2 lines.

how can I do that in java? ....because I doesn't want to let much objects in memory...

thank u!


Solution

  • If you know the offset you want to jump at (and not only a line number), then you could use a RandomAccessFile and the skip method. In your case, if your lines are really all equals, you could compute the offset and jump.

    Otherwise, if you just base your jump on line numbers, you will have to read all the file, line by line using a BufferedReader or using a FilterReader or by buffering a huge tab of chars and counting line by yourself, whatever you want, and start considering only the portion of data you want.

    Another good option for a huge volume of data is a database...

    Regards, Stéphane