How to put data from an OutputStream into a ByteBuffer?

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

    You say you're writing to this stream yourself? If so, maybe you could implement your own ByteBufferOutputStream and plug n' play.

    The base class would look like so:

    public class ByteBufferOutputStream extends OutputStream {
        //protected WritableByteChannel wbc; //if you need to write directly to a channel
        protected static int bs = 2 * 1024 * 1024; //2MB buffer size, change as needed
        protected ByteBuffer bb = ByteBuffer.allocate(bs);
    
        public ByteBufferOutputStream(...) {
            //wbc = ... //again for writing to a channel
        }
    
        @Override
        public void write(int i) throws IOException {
            if (!bb.hasRemaining()) flush();
            byte b = (byte) i;
            bb.put(b);
        }
    
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            if (bb.remaining() < len) flush();
            bb.put(b, off, len);
        }
    
        /* do something with the buffer when it's full (perhaps write to channel?)
        @Override
        public void flush() throws IOException {
            bb.flip();
            wbc.write(bb);
            bb.clear();
        }
    
        @Override
        public void close() throws IOException {
            flush();
            wbc.close();
        }
        /*
    }
    

提交回复
热议问题