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.
The Files
class can be used to read the line of a file.
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 numbertry{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 line.
Note: The method has to be put inside a
try-catch
block in order to handle IO exceptions.
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 numberString 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.
For Java 7 users, the BufferedReader
class can be used to retrieve a particular line of text.
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 numberString 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);}}}