如何使用 Files.lines(...).forEach(...) 从文件中读取? [英] How to read from files with Files.lines(...).forEach(...)?

查看:30
本文介绍了如何使用 Files.lines(...).forEach(...) 从文件中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试从我拥有的纯文本文件中读取行.我在另一个 stackoverflow 上发现(在 Java 中读取纯文本文件)你可以使用 Files.lines(..).forEach(..)但是我实际上无法弄清楚如何使用 for each 函数来逐行读取文本,有人知道在哪里查找或如何查找吗?

I'm currently trying to read lines from a text only file that I have. I found on another stackoverflow(Reading a plain text file in Java) that you can use Files.lines(..).forEach(..) However I can't actually figure out how to use the for each function to read line by line text, Anyone know where to look for that or how to do so?

推荐答案

test.txt 的示例内容

Sample content of test.txt

Hello
Stack
Over
Flow
com

使用 lines()forEach() 方法从此文本文件读取的代码.

Code to read from this text file using lines() and forEach() methods.

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

public class FileLambda {

    public static void main(String args[]) {
        Path path = Paths.of("/root/test.txt");
        try (Stream<String> lines = Files.lines(path)) {
            lines.forEach(s -> System.out.println(s));
        } catch (IOException ex) {
          // do something or re-throw...
        }
    }
    
}

这篇关于如何使用 Files.lines(...).forEach(...) 从文件中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆