How to read a specific line using the specific line number from a file in Java?

trinity picture trinity · Feb 22, 2010 · Viewed 244.5k times · Source

In Java, is there any method to read a particular line from a file? For example, read line 32 or any other line number.

Answer

aioobe picture aioobe · Apr 14, 2015

For small files:

String line32 = Files.readAllLines(Paths.get("file.txt")).get(32)

For large files:

try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
    line32 = lines.skip(31).findFirst().get();
}