Write a stream into a file with NIO and the Channel system

java, nio

Solution

Have a look at the `Channels.newChannel(java.io.InputStream)` method.

newChannel

  public static ReadableByteChannel newChannel(InputStream in)

Constructs a channel that reads bytes from the given stream.

The resulting channel will not be buffered; it will simply redirect its I/O operations to the given stream. Closing the channel will in turn cause the stream to be closed.

Parameters:`in` - The stream from which bytes are to be read Returns:A new readable byte channel

Problem

I have an inputStream and i want to write it to a file. I saw NIO and the FileChannel which has the method "transferTo" ou "transferFrom" and i know how to create the WriteableChannel, but i don't know to transform my inputStream to a ReadableChannel. Thanks.

Original source