简体   繁体   English

如何使用Java Stream逐行读取文件

[英]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 : 我将使用这3个String来创建图形数据结构,如:

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. 我知道我可以发送完整的字符串,但是因为我正在学习Stream我很想知道如何提取这些信息。

Thank you. 谢谢。

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]));

The method lines() you are using already does what you expect it to do. 您正在使用的方法lines()已经按照您的预期执行。

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. Java 8在Files类中添加了一个名为lines()的新方法,该方法可用于在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. 这种方法的优点在于它从文件中读取所有行作为Stream of String,当流被消耗时,它会被懒惰地填充。 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. 因此,如果你有一个巨大的文件而你只读了前100行,那么其余的行将不会被加载到内存中,这会带来更好的性能。

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 eg 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. 这与Files.readAllLines()方法(将所有行读入List)略有不同,因为此方法只是在Stream上调用终端操作时才懒惰地读取文件,例如forEach()count()等。通过使用count()方法您可以通过过滤空行来实际计算文件中的行数或空行数。

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

Since you want to solve this problem and want to learn how streams can be useful in this situation 由于您希望解决此问题,并希望了解流在这种情况下如何有用

  1. Reading a file(Using Java8) , this will fetch you all the lines in the file : Stream lines = Files.lines(Paths.get(filePath)) 读取文件(使用Java8),这将获取文件中的所有行 :Stream lines = Files.lines(Paths.get(filePath))
  2. Reading this file line by line : lines.map(line -> line.split(pattern)) , by splitting the line and you will get three sections from the line 逐行读取此文件 :lines.map(line - > line.split(pattern)),通过拆分该行,您将从该行获得三个部分
  3. Passing the arguments obtained into the functio n : forEach(arg -> createGraphe(arg[0], arg[1], arg[2]); 将获得的参数传递给函数 :forEach(arg - > createGraphe(arg [0],arg [1],arg [2]);

I hope this is pretty elaborate for your answer if you want to achieve this 如果你想实现这个目标,我希望你的答案非常详细

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM