Reading a specific line from a text file in Java

Lluis Martinez picture Lluis Martinez · Jan 26, 2010 · Viewed 30k times · Source

Is there any method to read a specific line from a text file ? In the API or Apache Commons. Something like :

String readLine(File file, int lineNumber)

I agree it's trivial to implement, but it's not very efficient specially if the file is very big.

Answer

Bozho picture Bozho · Jan 26, 2010
String line = FileUtils.readLines(file).get(lineNumber);

would do, but it still has the efficiency problem.

Alternatively, you can use:

 LineIterator it = IOUtils.lineIterator(
       new BufferedReader(new FileReader("file.txt")));
 for (int lineNumber = 0; it.hasNext(); lineNumber++) {
    String line = (String) it.next();
    if (lineNumber == expectedLineNumber) {
        return line;
    }
 }

This will be slightly more efficient due to the buffer.

Take a look at Scanner.skip(..) and attempt skipping whole lines (with regex). I can't tell if it will be more efficient - benchmark it.

P.S. with efficiency I mean memory efficiency