Java: Reading the Nth line from a file

Here's how to retrieve a line at a specific line number from a file.

For small files:

String line = Files.readAllLines(Paths.get("file.txt")).get(n);

For large files:

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

Java 7

String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    for (int i = 0; i < n; i++)
    line = br.readLine();


Be the first to comment!