Skip to content

Read nth line from file using Java 8 stream

Let’s take a file sample.txt which has the following contents.

1. A bad workman always blames his tools.
2. A bird in hand is worth two in the bush.
3. Absence makes the heart grow fonder.
4. A cat has nine lives.
5. A chain is only as strong as its weakest link.
Advertisements

To read the 3rd line using Java 8 stream, we can use the following code snippet.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
.

.
  
.
  
int lineNumber = 3;
 String str = Files.lines(Paths.get("/home/subash/Documents/sample.txt")).skip(lineNumber - 1).findFirst().get();
System.out.println(str); 
//3. Absence makes the heart grow fonder.

If the line number is not present this would throw NoSuchElementException

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.