Java 8 – Stream of lines读取文件

本文介绍了如何使用Java 8的Stream API逐行读取文件。通过示例展示了如何过滤包含特定词汇的行,并使用try-with-resources进行资源管理。
摘要由CSDN通过智能技术生成

Java 8 – Stream of lines

在下面的实例中,将使用Stream来一行一行的读取文件
将要读取的文件 data.txt 内容如下:

Lokesh
Gupta
Never
store
password
except
in mind.

将上面的文件一行一行的读取,如果有一行包含 password ,将这行打印出来

1. Read file line by line – Java 8 Stream

利用Java 8 Stream读取文件内容,过滤包含 password 的行,并取出第一条打印出来

private static void readStreamOfLinesUsingFiles() throws IOException
{
    Stream<String> lines = Files.lines(Paths.get("c:/temp", "data.txt"));
 
    Optional<String> hasPassword = lines.filter(s -> s.contains("password")).findFirst();
 
    if(hasPassword.isPresent())
    {
        System.out.println(hasPassword.get());
    }
 
    //Close the stream and it's underlying file as well
    lines.close();
}

2. Read file line by line – FileReader

直到java7,可采用下面的方式来读取文件,实现方法有很多,但不是本文的重点,只是与上面的例子对比来看

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();
}

3. Read file as stream of lines – try-with-resources

第一个例子已经能够满足我们在应用程序中逐行读取文件的需要了, 但如果你还想让它变得更好, 那么我们可以使用 try-with-resources 的方式, 这样会省去最后关闭流 close() 的操作。

private static void readStreamOfLinesUsingFilesWithTryBlock() throws IOException
{
    Path path = Paths.get("c:/temp", "data.txt");
 
    //The stream hence file will also be closed here
    try(Stream<String> lines = Files.lines(path))
    {
        Optional<String> hasPassword = lines.filter(s -> s.contains("password")).findFirst();
 
        if(hasPassword.isPresent()){
            System.out.println(hasPassword.get());
        }
    }
}

当一个Stream产生另外一个Stream的时候,close 方法会链式调用(它下面的Stream也会调用),可以采用下面的方法编写:

private static void readStreamOfLinesUsingFilesWithTryBlock() throws IOException
{
    Path path = Paths.get("c:/temp", "data.txt");
 
    //When filteredLines is closed, it closes underlying stream as well as underlying file.
    try(Stream<String> filteredLines = Files.lines(path).filter(s -> s.contains("password")))
    {
        Optional<String> hasPassword = filteredLines.findFirst();
 
        if(hasPassword.isPresent()){
            System.out.println(hasPassword.get());
        }
    }
}

你想测试一下它下面的Stream的有没有触发 close ,可以用 onClose 来测试一下

private static void readStreamOfLinesUsingFilesWithTryBlock() throws IOException
{
    Path path = Paths.get("c:/temp", "data.txt");
    //When filteredLines is closed, it closes underlying stream as well as underlying file.
    try(Stream<String> filteredLines = Files.lines(path)
                                    //test if file is closed or not
                                    .onClose(() -> System.out.println("File closed"))
                                    .filter(s -> s.contains("password"))){
        Optional<String> hasPassword = filteredLines.findFirst();
        if(hasPassword.isPresent()){
            System.out.println(hasPassword.get());
        }
    }
}

输出

password
File closed

翻译自:https://howtodoinjava.com/java8/read-file-line-by-line-in-java-8-streams-of-lines-example/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值