Reading the Nth line from a file in Java

Java supports several file-reading features. One such utility is reading a specific line in a file.

We can do this by simply providing the desired line number; the stream will read the text at that location.

svg viewer

The Files class can be used to read the nthnth line of a file.

Small files

main.java
file.txt
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class FileRead {
public static void main( String args[] ) {
int n = 1; // The line number
try{
String line = Files.readAllLines(Paths.get("file.txt")).get(n);
System.out.println(line);
}
catch(IOException e){
System.out.println(e);
}
}
}

The readAllLines method returns a list of strings where​ each string is a line of text in the specified file. get(n) retrieves the string for the nthnth line.

Note: The method has to be put inside a try-catch block in order to handle IO exceptions.

Large files

main.java
file.txt
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.*;
class FileRead {
public static void main( String args[] ) {
int n = 40; // The line number
String line;
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
line = lines.skip(n).findFirst().get();
System.out.println(line);
}
catch(IOException e){
System.out.println(e);
}
}
}

In the code above, lines.skip is used to jump n lines from the start of the file. Just as before, the get() method returns a string.

Java 7

For Java 7 users, the BufferedReader class can be used to retrieve a particular line of text.

main.java
file.txt
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
class FileRead {
public static void main( String args[] ) {
int n = 40; // The line number
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
for (int i = 0; i < n; i++)
br.readLine();
line = br.readLine();
System.out.println(line);
}
catch(IOException e){
System.out.println(e);
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved