Java ByteBuffer to Byte Array toByteArray(ByteBuffer buffer, int length)

Here you can find the source of toByteArray(ByteBuffer buffer, int length)

Description

Returns an array (that shouldn't be written to!) of the ByteBuffer.

License

Apache License

Declaration

public static byte[] toByteArray(ByteBuffer buffer, int length) 

Method Source Code


//package com.java2s;
/* NOTICE: This file has been changed by Plutext Pty Ltd for use in docx4j.
 * The package name has been changed; there may also be other changes.
 * /*w w  w. jav a2 s .c  om*/
 * This notice is included to meet the condition in clause 4(b) of the License. 
 */

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.nio.ByteBuffer;

public class Main {
    /**
     * Reads all the data from the input stream, and returns the bytes read.
     */
    public static byte[] toByteArray(InputStream stream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[4096];
        int read = 0;
        while (read != -1) {
            read = stream.read(buffer);
            if (read > 0) {
                baos.write(buffer, 0, read);
            }
        }

        return baos.toByteArray();
    }

    /**
     * Returns an array (that shouldn't be written to!) of the
     *  ByteBuffer. Will be of the requested length, or possibly
     *  longer if that's easier.
     */
    public static byte[] toByteArray(ByteBuffer buffer, int length) {
        if (buffer.hasArray() && buffer.arrayOffset() == 0) {
            // The backing array should work out fine for us
            return buffer.array();
        }

        byte[] data = new byte[length];
        buffer.get(data);
        return data;
    }
}

Related

  1. toByteArray(ByteBuffer buffer)
  2. toByteArray(ByteBuffer buffer)
  3. toByteArray(ByteBuffer buffer)
  4. toByteArray(ByteBuffer buffer)
  5. toByteArray(ByteBuffer buffer, int length)
  6. toByteArray(ByteBuffer bytes)
  7. toByteArrayByByteBuffer(int value)
  8. toBytes(ByteBuffer buff)
  9. toBytes(ByteBuffer buffer)