Java 8 streaming to file

There is already an answer to this question: > modify file using files lines1

For reading, there is a good file Lines method, so I think there must be a symmetrical method to write to the file, but I can't find one Files. Write requires only one iteration

Solution

The easiest way is to use files Write and trick to convert stream to 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 shocking, use a more explicit method:

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 some custom object streams, you can add them at any time Map (object:: toString) step to apply toString () method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>