tags:

views:

203

answers:

3

Lets say I have 10 lines in a file. I have 2 parameters that specify the beginning and ending of a index.

StartIndex = 2 // specifies the first 2 lines

EndIndex = 3 // specifies the last 3 lines

I need to read the lines in between. I know maintaining index and skipping is one of the ways...but are there any other efficient ways (even with external libraries)?

Thanks

A: 

I guess you're asking if there is anyway to jump directly to the third line of the file without reading the first two lines. In general (unless you have an index, as you mentioned) the answer is no. You have to read the first two lines to know how long they are, so the simple solution of reading the file line-by-line and ignoring the first lines is about as good as you can get.

Regarding the end, if your end index is an index from the beginning of the file then you can stop early. But did you mean the 3rd line from the end of the file? In this case you will also have to read all the way to the end of the file to know when to stop.

One special case is if you know that all the lines are the same length. Then you can seek directly to the correct location in the file and start reading from there.

Mark Byers
I guess I mentioned the same in the post, use index to do a file scan...
HonorGod
A: 

Using the commons IO you can do it easily, but it is not efficient because it will load the whole file in memory.

File file = new File("myfile.txt");
List lines = FileUtils.readLines(file).subList(2,3);

http://commons.apache.org/io/

Dominique
A: 

As the other guys pointed out, unless you know more information about the content of the file then no and you really have to read sequentially to find out where the lines begins. You can make use of LineNumberReader which is a buffered character-input stream that keeps track of line numbers.

fikovnik