How to put the content of a ByteBuffer into an OutputStream?

試著忘記壹切 提交于 2019-11-30 11:18:17

问题


I need to put the contents of a java.nio.ByteBuffer into an java.io.OutputStream. (wish I had a Channel instead but I don't) What's the best way to do this?

I can't use the ByteBuffer's array() method since it can be a read-only buffer.

I also may be interspersing writes to the OutputStream between using this ByteBuffer and having a regular array of byte[] which I can with use OutputStream.write() directly.


回答1:


Look at Channels.newChannel(OutputStream). It will give you a channel given an OutputStream. With the WritableByteChannel adapter you can provide the ByteBuffer which will write it to the OutputStream.

public void writeBuffer(ByteBuffer buffer, OutputStream stream) {
   WritableByteChannel channel = Channels.newChannel(stream);

   channel.write(buffer);
}

This should do the trick!



来源:https://stackoverflow.com/questions/579600/how-to-put-the-content-of-a-bytebuffer-into-an-outputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!