Java 8 流到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32054180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:59:57  来源:igfitidea点击:

Java 8 stream to file

javajava-8java-stream

提问by knub

Suppose I have a java.util.stream.Streamof objects with some nice toStringmethod: What's the shortest/most elegant solution to write this stream to a file, one line per stream element?

假设我有一个java.util.stream.Stream带有一些不错toString方法的对象:将此流写入文件最短/最优雅的解决方案是什么,每个流元素一行?

For reading, there is the nice Files.linesmethod, so I thought there must be a symmetric method for writing to file, but could not find one. Files.writeonly takes an iterable.

对于读取,有一个很好的Files.lines方法,所以我认为必须有一种写入文件的对称方法,但找不到。 Files.write只需要一个迭代。

采纳答案by Tagir Valeev

Probably the shortest way is to use Files.writealong with the trickwhich converts the Streamto the Iterable:

可能最短的方法是Files.write与将 the 转换为 the的技巧一起使用:StreamIterable

Files.write(Paths.get(filePath), (Iterable<String>)stream::iterator);

For example:

例如:

Files.write(Paths.get("/tmp/numbers.txt"),
     (Iterable<String>)IntStream.range(0, 5000).mapToObj(String::valueOf)::iterator);

If it looks too hackish, use more explicit approach:

如果它看起来太hackish,请使用更明确的方法:

try(PrintWriter pw = new PrintWriter(Files.newBufferedWriter(
                     Paths.get("/tmp/numbers.txt")))) {
    IntStream.range(0, 5000).mapToObj(String::valueOf).forEach(pw::println);
}

If you have stream of some custom objects, you can always add the .map(Object::toString)step to apply the toString()method.

如果您有一些自定义对象的流,您可以随时添加.map(Object::toString)应用该toString()方法的步骤。