2015-06-12 36 views
3

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

回答

0

你可以從另一端嘗試:而不是包裝ByteArrayOutputStream成一個通道,你可以換你FileChannelOutputStream,並通過調用out.writeTo完成寫:

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

你的方法更改爲生成ByteArrayOutputStream。這是一種很差的技術,並沒有擴展。傳遞一個OutputStreamWriteableByteChannel,並讓它寫出它自己的輸出。