Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file-io

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

like image 794
trinity Avatar asked Feb 22 '10 17:02

trinity


People also ask

How do I read a specific line from a file?

Use readlines() to Read the range of line from the File You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python. We read the entire file using this way and then pick specific lines from it as per our requirement.

How do I read the contents of a file line by line?

The line must be terminated by any one of a line feed ("\n") or carriage return ("\r"). In the following example, Demo. txt is read by FileReader class. The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed.

How do you read a specific string in Java?

The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.


2 Answers

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(); } 
like image 84
aioobe Avatar answered Sep 20 '22 15:09

aioobe


Unless you have previous knowledge about the lines in the file, there's no way to directly access the 32nd line without reading the 31 previous lines.

That's true for all languages and all modern file systems.

So effectively you'll simply read lines until you've found the 32nd one.

like image 20
Joachim Sauer Avatar answered Sep 22 '22 15:09

Joachim Sauer