Writing content of ByteArrayOutputStream to file using NIO FileChannel
I have a method that generates ByteArrayOutputStream
and I want to put this content into a file using FileChannel
. With help FileOutputStream
I could do this:
ByteArrayOutputStream baos = MyClass.myMethod(); // get my stream
FileOutputStream out = new FileOutputStream("somefile"); // I want to write to "somefile"
out.writeTo(baos); // write
How do I do this using FileChannel
? I know I can convert baos
to a byte array and then convert to ByteBuffer
, and then I can finally use FileChannel.write()
to write stuff. But that would mean dumping the contents of the stream into memory, and it's quite large.
If I am wrong, converting ByteArrayOutputStream
to InputStream
some type and then using Channels.newChannel(InputStream in)
to finally use FileChannel.transferFrom()
will face the same problem.
source to share
You can try it from the other end: instead of wrapping ByteArrayOutputStream
in a pipe, you can wrap yours FileChannel
in OutputStream
and end the recording by calling out.writeTo
:
ByteArrayOutputStream baos = MyClass.myMethod1();
FileChannel channel = MyClass.myMethod2();
OutputStream out = Channels.newOutputStream(channel);
out.writeTo(baos);
source to share