Reading a specific line from a text file in Java
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
Not that I'm aware of.
Be aware that there's no particular indexing on files as to where the line starts, so any utility method would be exactly as efficient as:
BufferedReader r = new BufferedReader(new FileReader(file));
for (int i = 0; i < lineNumber - 1; i++)
{
r.readLine();
}
return r.readLine();
(with appropriate error-handling and resource-closing logic, of course).