读取文件 - JAVA8方法

本文介绍了如何在Java8中使用Files.lines方法将文件内容读取为Stream,便于进行过滤、转换等操作。示例代码展示了读取lines.txt文件,过滤掉以'line3'开头的行,并将所有内容转换为大写,最后存储到List中并打印。此外,还对比了使用BufferedReader结合Stream的方法来读取文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA8 中, 新增的可以使用 Files.lines 将文件内容读取为 Stream ,从而进行操作.

文件内容如下:

c://lines.txt – A simple text file for testing

line1
line2
line3
line4
line5
  1. JAVA 8 Read File + Stream
public static void main(String args[]) {

        String fileName = "c://lines.txt";

        //read file into stream, try-with-resources
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

            stream.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

输出

line1
line2
line3
line4
line5
  1. Java8 Read File + Stream + Extra
public static void main(String args[]) {

        String fileName = "c://lines.txt";
        List<String> list = new ArrayList<>();

        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

            //1. filter line 3
            //2. convert all content to upper case
            //3. convert it into a List
            list = stream
                    .filter(line -> !line.startsWith("line3"))
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }

        list.forEach(System.out::println);

    }

输出:

LINE1
LINE2
LINE4
LINE5
  1. 利用BufferedReader + Stream
public static void main(String args[]) {

        String fileName = "c://lines.txt";
        List<String> list = new ArrayList<>();

        try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {

            //br returns as stream and convert it into a List
            list = br.lines().collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
    
        list.forEach(System.out::println);

    }

输出:

line1
line2
line3
line4
line5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值