In this tutorials, I am going to show you how to read a File line by line using Java 8 Lambda Expressions.

Read File Line By Line :

Files is a class introduced in Java 7. This class consists exclusively of static methods that will work on files, directories, or other types of files.

Java 8 Read File Line By Line :

Java 8 introduced a method  lines(Path path) used to read all lines from a File as a Java 8 Stream and returns the Stream object.

Java 8 Read File Example :

Create a text file to read.

Sample.txt


Java 8 Streams
Java 8 Filters
Java 8 Read File Example
Java 8 List to Map Conversion
Spring
Hibernate
JQuery

Reading the above file line by line.


package com.onlinetutorialspoint.java8;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8_ReadaFile {
    public static void main(String[] args) {
        String filePath = "/home/chandrashekhar/Desktop/Sample";
        try (Stream<String> stream = Files.lines(Paths.get(filePath))) {

            stream.forEach(System.out::println);

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

On the above example we have used an extreme feature of Java 7 try with resources to manage the Automatic Resource Management (ARM) in Java.

[box type=”success” align=”alignleft” class=”” width=”100%”]

Java 8 Streams
Java 8 Filters
Java 8 Read File Example
Java 8 List to Map Conversion
Spring
Hibernate
JQuery

[/box]

We can also filter the file data using Java 8 stream filtering.

Java 8 Read File with Filter :

We can filter the file data while reading the file itself using the Java 8 Stream API.

package com.onlinetutorialspoint.java8;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Java8_ReadaFile_Filter {
    public static void main(String[] args) {
        String filePath = "/home/chandrashekhar/Desktop/Sample";
        List<String> lines = new ArrayList<>();
        try (Stream<String> stream = Files.lines(Paths.get(filePath))) {

            lines = stream
                    .filter(line -> line.startsWith("Java"))
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
        lines.forEach(System.out::println);
    }
}

On the above example we have apply the filter on file data with Java keyword, and the data converted as upper case.

[box type=”shadow” align=”alignleft” class=”” width=”100%”]

JAVA 8 STREAMS
JAVA 8 FILTERS
JAVA 8 READ FILE EXAMPLE
JAVA 8 LIST TO MAP CONVERSION

[/box]

Happy Learning 🙂