Java ByteBuffer Put readAsByteBuffer(final InputStream source)

Here you can find the source of readAsByteBuffer(final InputStream source)

Description

Reads everything from the input stream using NIO and returns a byte buffer.

License

Open Source License

Parameter

Parameter Description
source input stream

Exception

Parameter Description
IOException an exception

Return

resultant byte buffer

Declaration

public static ByteBuffer readAsByteBuffer(final InputStream source) throws IOException 

Method Source Code


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

Related

  1. putVarint(ByteBuffer buffer, long number, int byteSize)
  2. putVInt(ByteBuffer b, int i)
  3. putWhatFits(ByteBuffer dest, ByteBuffer src)
  4. putWithChecksum(ByteBuffer buffer, int value, Adler32 checksum)
  5. read(InputStream is, ByteBuffer buf, int bytes)
  6. readBER32(ByteBuffer input)
  7. readByteBuffer(DataInputStream is)
  8. readByteBufferList(DataInputStream is)
  9. readBytes(InputStream is, ByteBuffer buffer)