Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file line by line with Java Stream

I'm trying to read a long file line by line and trying in the same time to extract some information from the line.

Here in an example of what i'm doing:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Stream;

public class ReadFile_Files_Lines {

    public static void main(String[] pArgs) throws IOException {
        String fileName = "c:\\temp\\sample-1GB.txt";
        File file = new File(fileName);

        try (Stream<String> linesStream = Files.lines(file.toPath())) {
            linesStream.forEach(line -> {
                System.out.println(line);
            });
        }
    }
}

One line in my file is devided into three part :

10 1010101 15

I'm looking to read those three informations every time. Like :

String str1 = line[0];
String str2 = line[1];
String str3 = line[2];

The solution i'm looking for will be better if i should not convert the stream to a collection. I will use those 3 String to create a graph data structure, something like :

createGraphe(str1,str2,str3);`

I know that i can send the full String, but as i'm learning Stream I'm interested to know how to extract those informations.

Thank you.

like image 269
xmen-5 Avatar asked Nov 19 '18 12:11

xmen-5


2 Answers

You can map to an array by splitting each line, then call the method you want.

Files.lines(filePath)
    .map(l -> l.split(" "))
    .forEach(a -> createGraphe(a[0], a[1], a[2]));
like image 164
daniu Avatar answered Nov 15 '22 12:11

daniu


The method lines() you are using already does what you expect it to do.

Java 8 has added a new method called lines() in Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed. So, if you have a huge file and you only read first 100 lines then rest of the lines will not be loaded into memory, which results in better performance.

This is slightly different than Files.readAllLines() method (which reads all lines into a List) because this method reads the file lazily, only when a terminal operation is called on Stream e.g. forEach(), count() etc. By using count() method you can actually count a number of lines in files or number of empty lines by filtering empty lines.

Reference: https://javarevisited.blogspot.com/2015/07/3-ways-to-read-file-line-by-line-in.html

like image 22
Pushpesh Kumar Rajwanshi Avatar answered Nov 15 '22 12:11

Pushpesh Kumar Rajwanshi