我有一種方法可以生成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()
會遇到同樣的問題。