簡體   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