Java ByteBuffer Put readFully(InputStream is, ByteBuffer buffer, int nrBytes)

Here you can find the source of readFully(InputStream is, ByteBuffer buffer, int nrBytes)

Description

Reads the given nr of bytes from the InputStream and writes them to the buffer.

License

Apache License

Parameter

Parameter Description
is The InputStream that will be read.
buffer The ByteBuffer that the bytes will be written to.
nrBytes The nr of bytes that will be read.

Exception

Parameter Description
IOException If something goes wrong while reading the InputStream.
EOFException When the InputStream does not have enough bytes left to be read.
IllegalArgumentException When the room remaining in the buffer is less that the nr of bytes given.

Declaration

public static void readFully(InputStream is, ByteBuffer buffer, int nrBytes) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

import java.nio.ByteBuffer;

public class Main {
    /**/*from   w  w w  .  j  av  a  2s .co  m*/
     * Reads the given nr of bytes from the InputStream and writes them to the buffer. When the nr of bytes is zero or
     * less, this method will not do anything.
     * 
     * @param is
     *            The {@link InputStream} that will be read.
     * @param buffer
     *            The {@link ByteBuffer} that the bytes will be written to.
     * @param nrBytes
     *            The nr of bytes that will be read.
     * @throws IOException
     *             If something goes wrong while reading the {@link InputStream}.
     * @throws EOFException
     *             When the {@link InputStream} does not have enough bytes left to be read.
     * @throws IllegalArgumentException
     *             When the room remaining in the buffer is less that the nr of bytes given.
     */
    public static void readFully(InputStream is, ByteBuffer buffer, int nrBytes) throws IOException {
        if (buffer.remaining() < nrBytes) {
            throw new IllegalArgumentException("There is not enough room left in the buffer to write " + nrBytes
                    + " bytes, there is only room for " + buffer.remaining() + " bytes");
        }
        for (int i = 0; i < nrBytes; i++) {
            int b = is.read();
            if (b < 0) {
                throw new EOFException();
            }
            buffer.put((byte) (b & 0xff));
        }
        buffer.flip();
    }
}

Related

  1. readByteBufferList(DataInputStream is)
  2. readBytes(InputStream is, ByteBuffer buffer)
  3. readByteVector8(ByteBuffer input)
  4. readFully(InputStream in, ByteBuffer out)
  5. readFully(InputStream is, ByteBuffer buf)
  6. readInto(ByteBuffer buf, InputStream inputStream)
  7. readNextLine(InputStream in, ByteBuffer buff, boolean acceptEOF, boolean requireCR)
  8. readPackedLong(ByteBuffer input)
  9. readToByteBuffer(InputStream inStream)