How to put data from an OutputStream into a ByteBuffer?

后端 未结 6 1846
庸人自扰
庸人自扰 2021-02-18 15:23

In Java I need to put content from an OutputStream (I fill data to that stream myself) into a ByteBuffer. How to do it in a simple way?

6条回答
  •  被撕碎了的回忆
    2021-02-18 15:49

    Though the above-mention answers solve your problem, none of them are efficient as you expect from NIO. ByteArrayOutputStream or MyByteArrayOutputStream first write the data into a Java heap memory and then copy it to ByteBuffer which greatly affects the performance.

    An efficient implementation would be writing ByteBufferOutputStream class yourself. Actually It's quite easy to do. You have to just provide a write() method. See this link for ByteBufferInputStream.

提交回复
热议问题