繁体   English   中英

写一个 Stream<string> 到文件 Java</string>

[英]Write a Stream<String> to a file Java

我正在使用 java NIO 包的Files.lines()方法读取文件,该方法给出了Stream<String>类型的 output 。 在对字符串记录进行一些操作后,我想将其写入文件。 我尝试使用Collectors.toList()将其收集到列表中,它适用于较小的数据集。 当我的文件有近 100 万行(记录)时,就会出现问题,该列表无法容纳尽可能多的记录。

// Read the file using Files.lines and collect it into a List
        List<String> stringList = Files.lines(Paths.get("<inputFilePath>"))
                                    .map(line -> line.trim().replaceAll("aa","bb"))
                                    .collect(Collectors.toList());


//  Writes the list into the output file
        Files.write(Paths.get("<outputFilePath>"), stringList);

我正在寻找一种方法,我可以读取一个大文件,操作它(如在我的示例中的.map()方法中所做的那样),并将其写入文件而不将其存储到列表(或集合)中。

你可以试试这个(更新代码以关闭资源):

    try (BufferedWriter writer = Files.newBufferedWriter(Path.of(outFile), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
         Stream<String> lines = Files.lines(Path.of(inFile))) {
        // Read the file using Files.lines and collect it into a List
        lines.map(line -> line.trim().replaceAll("aa", "bb"))
                .forEach(line -> {
                    try {
                        writer.write(line);
                        writer.newLine();
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                });
        writer.flush();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM