Java 8流到文件 [英] Java 8 stream to file

查看:216
本文介绍了Java 8流到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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.write 以及将 Stream 转换为<技巧 code> Iterable :

Probably the shortest way is to use Files.write along with the trick which converts the Stream to the Iterable:

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

例如:

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

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

If it looks too hackish, use more explicit approach:

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

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

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

这篇关于Java 8流到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆