I have a method that generates a ByteArrayOutputStream
and I want to put those contents in a file using FileChannel
. With 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 can I do this using FileChannel
? I know I can convert baos
to a byte array, then convert that to a ByteBuffer
, and then I can finally use FileChannel.write()
to write stuff. But this would mean dumping the contents of the stream into memory and it is fairly large.
Unless I'm mistaken, converting the ByteArrayOutputStream
into an InputStream
of some kind, and then using Channels.newChannel(InputStream in)
, to finally use FileChannel.transferFrom()
will run into the same problem.
You could try it from the other end: rather than wrapping
ByteArrayOutputStream
into a channel, you could wrap yourFileChannel
intoOutputStream
, and complete the write by callingout.writeTo
: