ByteBuffer from Stream - Java java.nio

Java examples for java.nio:ByteBuffer Stream

Description

ByteBuffer from Stream

Demo Code


//package com.java2s;
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);/*from   w ww .  j a  v  a 2 s .  c o  m*/

        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);
    }
}

Related Tutorials