使用Stream读取文件

Java8 以后的新特性比较好用,可以极大的简化代码,今天我们就一起来学习下如何使用新特性来读取文件的内容

/**
* 这里使用到了 nio中的Path nio是一种高性能的io读写操作
*/
    private static Stream<String> createStreamFromFile(){
        Path path = Paths.get("E:\\Rxjava2xdemo\\src\\LambdaUsage.java");
        //使用 Files.lines(opath) 将文件的内容一行一行的取出来形成一个Stream
        try(Stream<String> lines = Files.lines(path)){
            lines.forEach(System.out::println);
            return lines;
        }catch (IOException e){
                throw new IOException();
        }
        return null;
    }
posted @ 2022-04-03 23:08  飞航之梦  阅读(28)  评论(0)    收藏  举报