Here you can find the source of toByteArray(ByteBuffer buffer, int length)
public static byte[] toByteArray(ByteBuffer buffer, int length)
//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; } }