Reading a File at a Given Line Number in Java

Learn to read a specific line from a text file in Java. We will learn to write the solution for small files as well as large files as well.

1. Reading the Line in a Small File

If the file is small, we can afford to read the whole file into memory using a method that returns the file content as List of strings.

Once we have the List of strings, we can read any line using the suitable index in method list.get().

Path filePath = Paths.get("C:/temp/file.txt");

List<String> lines = null;
try {
  	lines = Collections.unmodifiableList(Files.readAllLines(filePath));
} catch (IOException e) {
  	e.printStackTrace();
}

//Read second line
String secondLine = lines.get(1);

Remember that list and array indices start from zero.

3. Reading the Specific Line in a Large File

Using the lines() method, the contents of a large file are read and processed lazily in form of Stream. As streams are lazily processed, we can use skip() method to leave certain line numbers and then start reading at the desired place.

Path filePath = Paths.get("C:/temp/file.txt")
 
//try-with-resources
try (Stream<String> streamOfLines = Files.lines( filePath ))
{
  String secondLine = streamOfLines.skip(1)
      .findFirst()
      .get();
}
catch (IOException e)
{
  e.printStackTrace();
}

3. Conclusion

In this short tutorial, we learned to read a specific line number in Java. We saw two solutions where Files.lines() can be used for small and large files.

The first solution, Files.readAllLines() is suitable for only small files.

Happy Learning !!

Source Code on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial