Java 8从CSV流过滤行,但保留第一行

我想从CSV文件中删除包含错误日期的行。在此过程中,CSV文件应保留标题行。我想使用Java 8流执行所有这些操作。

起初我想到了这个:

try (Stream<String> linesUnfiltered = Files.lines(f.toPath(), StandardCharsets.UTF_8)) {
    Stream<String> firstLine = linesUnfiltered.limit(1);
    Stream<String> linesFiltered = linesUnfiltered
            .filter(e -> e.contains(sdfFileContent.format(fileDate)));
    Stream<String> result = Stream.concat(firstLine, linesFiltered);
    Files.write(f.toPath(), (Iterable<String>) result::iterator);
}

But this throws the exception java.lang.IllegalStateException: stream has already been operated upon or closed because linesUnfiltered is reused. The suggestion on the web is to use a Supplier<Stream<String>>, but my understanding is that the supplier would read the file for each supplier.get() call, which is not very efficient.

这就是为什么我要问是否还有另一种方法比这更有效?我非常确定,应该可以在同一流上执行两个操作...

编辑:

这不是重复项,因为不应删除第一项。它仅应从过滤过程中排除,但仍可在结果流中使用

评论