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
Java 8 stream to file
提问by knub
Suppose I have a java.util.stream.Stream
of objects with some nice toString
method:
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.lines
method, so I thought there must be a symmetric method for writing to file, but could not find one.
Files.write
only takes an iterable.
对于读取,有一个很好的Files.lines
方法,所以我认为必须有一种写入文件的对称方法,但找不到。
Files.write
只需要一个迭代。
采纳答案by Tagir Valeev
Probably the shortest way is to use Files.write
along with the trickwhich converts the Stream
to the Iterable
:
可能最短的方法是Files.write
与将 the 转换为 the的技巧一起使用:Stream
Iterable
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()
方法的步骤。