Wrapping a ByteBuffer with an InputStream

后端 未结 6 1457
青春惊慌失措
青春惊慌失措 2020-12-01 04:46

I have a method that takes an InputStream and reads data from it. I would like to use this method with a ByteBuffer also. Is there a way to wrap a ByteBuffer so it can be ac

6条回答
  •  温柔的废话
    2020-12-01 05:26

    Use the heap buffer (byte array) directly if available, otherwise use wrapped bytebuffer (see answer Mike Houston)

    public static InputStream asInputStream(ByteBuffer buffer) {
        if (buffer.hasArray()) {
            // use heap buffer; no array is created; only the reference is used
            return new ByteArrayInputStream(buffer.array());
        }
        return new ByteBufferInputStream(buffer);
    }
    

    Also note that the wrapped buffer can efficiently support the mark/reset and skip operations.

提交回复
热议问题