robi
robi

Reputation: 167

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!

Upvotes: 0

Views: 6354

Answers (4)

jfg956
jfg956

Reputation: 16750

Do not use readline() as it will allocate useless String. Call read() on a BufferedReader, counting the number of '\n' until you have skip the number of lines you want.

Edit:

You might also have to count the `\r' and '\r' immediately followed by a '\n' to do exactly the same as readline(). You might have a small problem when you read the last '\r' as you cannot know if it is followed by a '\n' or not. To handle this case, I woult read the next char, and if it is not a '\n', I would use it in front of the 1st important line.

Another solution if your lines are of fixed size as in your example it to compute the number of chars to skip and use the BufferedReader.skip() method.

Upvotes: 0

Snicolas
Snicolas

Reputation: 38168

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

Upvotes: 2

talnicolas
talnicolas

Reputation: 14053

You don't have to store the value returned by readLine() at each calls, just check if it starts by the value you want. If it does, then you can store the lines you want.

Upvotes: 1

MByD
MByD

Reputation: 137332

A new line in a file is just a character. It is the same in Java, C and any other language, you'll have to use readLine() or similar method to count the lines. Even if there is a library that'll do it for you, it will still have to go char by char to count the lines.

Upvotes: 1

Related Questions