Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicReference; public class Main { private static final int BUFFER_SIZE = 16384; private static final AtomicReference<byte[]> BUFFER_REF = new AtomicReference<>(); public static ByteBuffer fromStream(InputStream stream) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(BUFFER_SIZE); byte[] buffer = BUFFER_REF.getAndSet(null); if (buffer == null) { buffer = new byte[BUFFER_SIZE]; } int n = -1; while ((n = stream.read(buffer)) >= 0) { outStream.write(buffer, 0, n); } BUFFER_REF.set(buffer); byte[] bytes = outStream.toByteArray(); // Some resource decoders require a direct byte buffer. Prefer allocateDirect() over wrap() return (ByteBuffer) ByteBuffer.allocateDirect(bytes.length).put(bytes).position(0); } }