我有一种方法可以生成ByteArrayOutputStream
,我想用FileChannel
将这些内容放入文件中。随着FileOutputStream
,我可以这样做:使用NIO FileChannel将ByteArrayOutputStream的内容写入文件
ByteArrayOutputStream baos = MyClass.myMethod(); // get my stream
FileOutputStream out = new FileOutputStream("somefile"); // I want to write to "somefile"
out.writeTo(baos); // write
我怎样才能做到这一点使用FileChannel
?我知道我可以将baos
转换为一个字节数组,然后将其转换为ByteBuffer
,然后我终于可以使用FileChannel.write()
来编写东西。但这意味着将流内容转储到内存中,并且它相当大。
除非我记错了,转换成ByteArrayOutputStream
某种类型的InputStream
,然后用Channels.newChannel(InputStream in)
,到最后使用FileChannel.transferFrom()
会遇到同样的问题。