Writing contents of ByteArrayOutputStream to a file using NIO FileChannel

2.5k views Asked by At

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.

2

There are 2 answers

0
Sergey Kalinichenko On

You could try it from the other end: rather than wrapping ByteArrayOutputStream into a channel, you could wrap your FileChannel into OutputStream, and complete the write by calling out.writeTo:

ByteArrayOutputStream baos = MyClass.myMethod1();
FileChannel channel = MyClass.myMethod2();
OutputStream out = Channels.newOutputStream(channel);
out.writeTo(baos);
0
user207421 On

Change your method to not generate a ByteArrayOutputStream. It's poor technique, and doesn't scale. Pass it an OutputStream, or WriteableByteChannel, and have it write its own output.