tags:

views:

614

answers:

5

In Java, is there any method to read a particular line from a file, for example, read line 32?

+5  A: 

Unless you have previous knowledge about the lines in the file, there's no way to directly access the 32nd line without reading the 31 previous lines.

That's true for all languages and all modern file systems.

So effectively you'll simply read lines until you've found the 32nd one.

Joachim Sauer
The "previous knowledge" can be as simple as exact line size pattern in the file so you can seek to a certain position.
Murali VP
@Murali: of course. It could also be an index of line number to byte offset or any combination thereof.
Joachim Sauer
+1  A: 

If you are talking about a text file, then there is really no way to do this without reading all the lines that precede it - After all, lines are determined by the presence of a newline, so it has to be read.

Use a stream that supports readline, and just read the first X-1 lines and dump the results, then process the next one.

Uri
+4  A: 

Not that I know of, but what you could do is loop through the first 31 lines doing nothing using the readline() function of BufferedReader

FileInputStream fs= new FileInputStream("someFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < 30; ++i)
  br.readLine();
String lineIWant = br.readLine();
Chris Thompson
Why the `DataInputStream`?
Joachim Sauer
That is an excellent question, I copied some old code and wasn't thinking...
Chris Thompson
+1  A: 

No, unless in that file format the line lengths are pre-determined (e.g. all lines with a fixed length), you'll have to iterate line by line to count them.

Bruno Rothgiesser
A: 

Joachim is right on, of course, and an alternate implementation to Chris' (for small files only because it loads the entire file) might be to use commons-io from Apache (though arguably you might not want to introduce a new dependency just for this, if you find it useful for other stuff too though, it could make sense).

For example:

String line32 = (String) FileUtils.readLines(file).get(31);

http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readLines(java.io.File, java.lang.String)

Charlie Collins
Though that would load the whole file into memory before going to the 32nd line, which might not be practical with a large file and would be slower than reading util finding the 32nd line...
beny23
Fair point, yes. I have used that in test cases, where the testing files were small, on large files though, agreed, not a good approach.
Charlie Collins
Updated answer post to reflect that FileUtils is a bad idea in this use case if you have a large file and don't need anything beyond line X.
Charlie Collins