Skip to content
Related Articles

Related Articles

BufferedReader Class lines() method in Java with Examples

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jan, 2021
View Discussion
Improve Article
Save Article

BufferedReader.lines() is the method of the  Java Buffered Reader Class in the Java Library which returns lines in terms of Stream and from this Buffered Reader class. With the help of the stream, there are a lot of methods that mimic the output according to our needs.

Syntax:

BufferedReader.lines() : Stream<String>

Parameters: This method does not take any kind of parameter.

Return: This method returns the stream of lines in terms of Stream and the Generic Type Change the stream into String.

Exception: IOException will be thrown when accessing the underlying BufferedReader which is wrapped in an UncheckedIOException.

Example: Find the line containing Hello as a word it will only work in a continuous scanning

  • The directory contains one txt files named as GFG.txt

  • The text File contains two lines: 


Java




// Java program to demonstrate the continuous scanning
// by BufferedReader.lines() method and return the stream
// of lines that contains the specific word
  
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
  
class GFG {
    public static void main(String[] args)
    {
        FileReader f= new FileReader("location of the file");
        
        BufferedReader b = new BufferedReader(f);
  
        // taking the stream as a string
        Stream<String> i = b.lines(); 
  
        i.filter(line -> line.contains("Hello")).findAny().ifPresent(System.out::println);
        
        // filter the stream that line contains Hello is
        // preset output
        b.close();
        f.close();
    }
}

Output:

Hello this is the first line. Hello this is the second line.
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!