开发者

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

开发者 https://www.devze.com 2023-03-26 12:50 出处:网络
I meet a big file(much GB),and I want to jump to specific line directly, and then read some line from that...

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!


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号