ByteBuffer to Stream - Java java.nio

Java examples for java.nio:ByteBuffer Stream

Description

ByteBuffer to Stream

Demo Code


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
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 void toStream(ByteBuffer byteBuffer, OutputStream os)
            throws IOException {
        SafeArray safeArray = getSafeArray(byteBuffer);
        if (safeArray != null) {
            os.write(safeArray.data, safeArray.offset, safeArray.offset
                    + safeArray.limit);//from www  . ja v  a2  s  .c om
        } else {
            byte[] buffer = BUFFER_REF.getAndSet(null);
            if (buffer == null) {
                buffer = new byte[BUFFER_SIZE];
            }

            while (byteBuffer.remaining() > 0) {
                int toRead = Math
                        .min(byteBuffer.remaining(), buffer.length);
                byteBuffer
                        .get(buffer, 0 /*dstOffset*/, toRead /*byteCount*/);
                os.write(buffer, 0, toRead);
            }

            BUFFER_REF.set(buffer);
        }
    }
    public static InputStream toStream(ByteBuffer buffer) {
        return new ByteBufferStream(buffer);
    }
    private static SafeArray getSafeArray(ByteBuffer byteBuffer) {
        if (!byteBuffer.isReadOnly() && byteBuffer.hasArray()) {
            return new SafeArray(byteBuffer.array(),
                    byteBuffer.arrayOffset(), byteBuffer.limit());
        }
        return null;
    }
}

Related Tutorials