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
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.