How to put data from an OutputStream into a ByteBuffer?

后端 未结 6 1841
庸人自扰
庸人自扰 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:47

    There is a more efficient variant of @DJClayworth's answer.

    As @seh correctly noticed, ByteArrayOutputStream.toByteArray() returns a copy of the backing byte[] object, which may be inefficient. However, the backing byte[] object as well as the count of the bytes are both protected members of the ByteArrayOutputStream class. Hence, you can create your own variant of the ByteArrayOutputStream exposing them directly:

    public class MyByteArrayOutputStream extends ByteArrayOutputStream {
      public MyByteArrayOutputStream() {
      }
    
      public MyByteArrayOutputStream(int size) {
        super(size);
      }
    
      public int getCount() {
        return count;
      }
    
      public byte[] getBuf() {
        return buf;
      }
    }
    

    Using this class is easy:

    MyByteArrayOutputStream out = new MyByteArrayOutputStream();
    fillTheOutputStream(out);
    return new ByteArrayInputStream(out.getBuf(), 0, out.getCount());
    

    As a result, once all the output is written the same buffer is used as the basis of an input stream.

提交回复
热议问题