Java 8 Stream - Read nth line from file

By Yashwant Chavan, Views 14171, Last updated on 05-Nov-2016

In this tutorial you will learn how to read nth line from file using java 8 stream API.

tags java

Refer below steps.

  • Paths.get("c:\\demo.txt") Locate a file in a file system.
  • Files.lines() Read all lines from a file as a Stream
  • Stream.skip(long n) Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream
  • Stream.findFirst() Returns an Optional describing the first element of this stream.
  • Get the value from Optional and print it on console.

demo.txt

one
two
three
four
five

Read nth line from file

package com.technicalkeeda.app;

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

public class Java8StreamReadNthLine {

    public static void main(String[] args) {

        int lineNumber = 2;

        try {
            String str = Files.lines(Paths.get("c:\\demo.txt")).skip(lineNumber - 1).findFirst().get();
            System.out.println("Content at " + lineNumber + " Number:- " + str);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

output

Content at 2 Number:- two

NoSuchElementException Exception

You will get NoSuchElementException if input index number is out of range.

Exception in thread "main" java.util.NoSuchElementException: No value present
 at java.util.Optional.get(Optional.java:135)
 at com.technicalkeeda.app.Java8StreamReadNthLine.main(Java8StreamReadNthLine.java:14)
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]