将 Stream<String> 写入文件 Java

Write a Stream<String> to a file Java

我正在使用 java NIO 程序包的 Files.lines() 方法读取文件,该方法给出类型为 Stream<String> 的输出。在对 String 记录进行一些操作后,我想将其写入文件。 我尝试使用 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() 方法中所做的那样),然后将其写入文件而不将其存储到列表中(或 collection).

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

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