真的简单,文本文件逐行处理–用java8 Stream流的方式

2020-10-17 15:46:15 蜻蜓队长

本文中为大家介绍使用java8 Stream API逐行读取文件,以及根据某些条件过滤文件内容

1. Java 8逐行读取文件

在此示例中,我将按行读取文件内容并在控制台打印输出。

Path filePath = Paths.get("c:/temp", "data.txt");
 
//try-with-resources语法,不用手动的编码关闭流
try (Stream<String> lines = Files.lines( filePath )) 
{
    lines.forEach(System.out::println);
} 
catch (IOException e) 
{
    e.printStackTrace();//只是测试用例,生产环境下不要这样做异常处理
}

上面的程序输出将在控制台中逐行打印文件的内容。

Never
store
password
except
in mind.

2.Java 8读取文件–过滤行

在此示例中,我们将文件内容读取为Stream。然后,我们将过滤其中包含单词"password"的所有行。

Path filePath = Paths.get("c:/temp", "data.txt");
 
try (Stream<String> lines = Files.lines(filePath)){
 
     List<String> filteredLines = lines
                    .filter(s -> s.contains("password"))
                    .collect(Collectors.toList());
      
     filteredLines.forEach(System.out::println);
 
} catch (IOException e) {
    e.printStackTrace();//只是测试用例,生产环境下不要这样做异常处理
}

程序输出。

password

我们将读取给定文件的内容,并检查是否有任何一行包含"password"然后将其打印出来。

3.Java 7 –使用FileReader读取文件

Java 7之前的版本,我们可以使用FileReader方式进行逐行读取文件。

private static void readLinesUsingFileReader() throws IOException 
{
    File file = new File("c:/temp/data.txt");
 
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
 
    String line;
    while((line = br.readLine()) != null)
    {
        if(line.contains("password")){
            System.out.println(line);
        }
    }
    br.close();
    fr.close();
}

欢迎关注我的博客,里面有很多精品合集

  • 本文转载注明出处(必须带连接,不能只转文字):字母哥博客
点击查看更多内容

以上内容来自于网络,如有侵权联系即删除
相关文章

上一篇: 数据结构之算法第一弹——链表的恩怨情仇(增删查改)

下一篇: MySQL 中常常被忽略的用户与权限

客服紫薇:15852074331
在线咨询
客户经理