Here you can find the source of readAsByteBuffer(final InputStream source)
Parameter | Description |
---|---|
source | input stream |
Parameter | Description |
---|---|
IOException | an exception |
public static ByteBuffer readAsByteBuffer(final InputStream source) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class Main { private static final int READ_BLOCK = 8192; /**// w ww .j a va 2s .c o m * Reads everything from the input stream using NIO and returns a byte buffer. * * @param source * input stream * @return resultant byte buffer * @throws IOException */ public static ByteBuffer readAsByteBuffer(final InputStream source) throws IOException { // create channel for input stream try (final ReadableByteChannel bc = Channels.newChannel(source)) { ByteBuffer bb = ByteBuffer.allocate(READ_BLOCK); while (bc.read(bb) != -1) { // read the data while it lasts in chunks defined by READ_BLOCK bb = resizeBuffer(bb); //resize the buffer if required to fit the data on the next read } bb.flip(); return bb; } } /** * A helper method to resize byte buffer upon read. * * @param in * @return */ private static ByteBuffer resizeBuffer(final ByteBuffer in) { if (in.remaining() < READ_BLOCK) { // create new buffer with double capacity final ByteBuffer result = ByteBuffer.allocate(in.capacity() * 2); // flip the in buffer in preparation for it to be copied into the newly created larger buffer in.flip(); // copy the in buffer into new buffer result.put(in); return result; } return in; } }