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();

Comments (2)

User avatar

Why do you call br.readLine() twice?

by Anonymous |  Reply
User avatar

The br.readLine() in the for loop discards lines. The second br.readLine() reads the line we're interested in.

by Andreas Lundblad |  Reply

Add comment