BufferedReader.lines() + Stream Examples in Java 8

Hello guy, in this article, I am going to tell you about a useful method from BufferedReader class, the lines() method which can be used to read a file line by line. The BufferedReader.lines() is kind of interesting, letting you turn a BufferedReader into a java.util.Stream in Java 8. This is a very powerful thing as it allows you to tread a file as a stream and then you can apply all sorts of Stream methods like map, count, flatMap, filter, distinct, etc to apply powerful transformation. We will actually see examples of those in this article by finding out the longest line from the file and printing each line of the file.


How to use BufferedReader.lines() + Stream in Java 8

Here are some useful examples by using the BufferedReader class and its lines() method which is newly added in Java 8 to find out the number of total lines from the file and printing the file line by line.

1. Print out the number of lines in a file:

This Java program can be used to find out the total number of lines in a given file using BufferedReader.lines() method which basically returns a stream and then we can use the count() method of Stream class to find out the total number of elements.


public static void main(String[] args) {
    try (BufferedReader reader = Files.newBufferedReader(
            Paths.get("myfile.txt"),
            StandardCharsets.UTF_8)) {
        System.out.println(reader.lines().count());
    } catch (IOException ex) {
    }
}



2. Print out all the lines:

This code can be used to read all the lines of a file in Java using BufferedReader.lines() method as shown below. You can see that we are using the forEach() method and method reference to print each line this is possible because the lines() method of BufferedReader returns a Stream and then you can use any Stream method to perform useful operations like counting or printing it element by element.

public static void main(String[] args) {
    try (BufferedReader reader = Files.newBufferedReader(
            Paths.get("myfile.txt"),
            StandardCharsets.UTF_8)) {
        reader.lines().forEach(System.out::println);
    } catch (IOException ex) {
    }
}



3. Print out the longest line in a file

This example is a little bit of elaborated and shows the power of Stream in Java. You can see that we first get the stream of lines using the lines() method and then mapped each line to their length to find out the longest line of the file.

public static void main(String[] args) {
    try (BufferedReader reader = Files.newBufferedReader(
            Paths.get("myfile.txt"),
            StandardCharsets.UTF_8)) {
        System.out.println(reader
                .lines()
                .mapToInt(String::length)
                .max()
                .getAsInt());
    } catch (IOException ex) {
    }
}


This is remarkable and considers doing this prior to Java 8, it wasn't that easy and that's why I really love streams. If you want to learn more about such gems, I highly recommend you to join the Learn Java Functional Programming with Lambdas & Streams course on Udemy to learn Stream and Lambdas in-depth and become a better Java developer.

BufferedReader.lines() + Stream Examples in Java 8




Java Program to use BufferedReader.lines() method 

The file used in this example is a Java manifest file created by Netbeans IDE for this program. Since the file is already in the classpath, we can access it by just specifying its name instead of the full path. The lines() method of BufferedReader returns a Stream with the lines read from this reader.

The best part of this method is that stream is lazily populated, only at the time of doing a terminal operation like forEach() for printing lines or count() to count the total number of lines.

manifest.mf
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build


import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Java Program to count number of lines in a file, 
 * print each line of file and
 * find length of longest line in file.
 *
 * @author Javin
 */
public class BufferedReaderJava8Demo{

    public static void main(String args[]) {

        // Using BufferedReader lines() method to print number of 
        // lines in a file
        try (BufferedReader reader = Files.newBufferedReader(
                Paths.get("manifest.mf"),
                StandardCharsets.UTF_8)) {
            
            long totalLinesInFile = reader.lines().count();
            System.out.println("Total number of lines in file is : " 
                             + totalLinesInFile);
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        
        

        // BufferedReader Example to print all lines of a file in Java 8
        try (BufferedReader reader = Files.newBufferedReader(
                Paths.get("manifest.mf"),
                StandardCharsets.UTF_8)) {
            
            System.out.println("Printing all lines in file manifest.mf 
                                 using Java 8 streams");
            reader.lines().forEach(System.out::println);
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // BufferedReader lines() Examples in Java 8
        // Let's find length of longest line in file
        try (BufferedReader reader = Files.newBufferedReader(
                Paths.get("manifest.mf"),
                StandardCharsets.UTF_8)) {
            
            long longestLineInFile = reader.lines()
                                           .mapToInt(String::length)
                                           .max()
                                           .getAsInt();
            System.out.println("Length of longest line in file : " 
                       + longestLineInFile);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

Output
Total number of lines in file is : 3
Printing all lines in file manifest.mf using Java 8 streams
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

Length of longest line in file : 58

Don't be surprised by seeing the total number of lines in the file manifest.mf as 3, because every Java manifest file contains an empty line at the bottom. Though you see only two lines, in reality, it is three lines, which is also picked by Java.

In the next example also this is evident because you can see an empty line after "X-COMMENT". Last example of BufferedReader prints the length of the longest line in a file, which is the second line, 58 characters long.

That's all about how to use BufferedReader in Java 8. By looking at these examples you can easily realize that Java 8 has put enormous power into BufferedReader. Now you can do lot of things with files and text in only a couple of lines.

The last example shows the true power of Java 8, imagine how would you find the length of the longest line in a File before Java 8. Once you do that, just think again that what if a file is 4GB or 10GB large in size. In Java 8, you can use the parallelStream() instead of the stream() to process large files using multiple threads without writing any additional code.


Further Learning
The Complete Java MasterClass
Java 8 New Features in Simple Way
Refactoring to Java 8 Streams and Lambdas Self- Study Workshop


Related Java 8 Tutorials

If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • 5 Books to Learn Java 8 from Scratch (books)
  • What is the default method in Java 8? (example)
  • How to use Stream class in Java 8 (tutorial)
  • 10 Free Courses to learn Spring Framework for Beginners (courses)
  • How to convert List to Map in Java 8 (solution)
  • Top 5 Courses to learn Java 8 in depth (courses)
  • How to join String in Java 8 (example)
  • Top 5 Courses to become a full-stack Java developer (courses)
  • How to use filter() method in Java 8 (tutorial)
  • How to format/parse the date with LocalDateTime in Java 8? (tutorial)
  • Difference between abstract class and interface in Java 8? (answer)
  • 20 Examples of Date and Time in Java 8 (tutorial)
  • How to use peek() method in Java 8 (example)
  • How to sort the map by keys in Java 8? (example)
  • How to sort the may by values in Java 8? (example)
  • 10 examples of Options in Java 8? (example)
  • 5 Courses to learn Functional Programming in Java (courses)

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or suggestions then please drop a comment.

P.S.: If you just want to learn more about new features in Java 8 then please see the What's New in Java 8 online course on Pluralsight. It explains all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API, and other miscellaneous changes.

No comments:

Post a Comment