Java InputStream Read Bytes readBytes(InputStream in, int maxLeng)

Here you can find the source of readBytes(InputStream in, int maxLeng)

Description

Reads a number of bytes from a stream.

License

LGPL

Parameter

Parameter Description
in input stream
maxLeng maximum number of bytes to read

Return

buffer of bytes containing maxLeng bytes read from in, or fewer if the stream ended early

Declaration

public static byte[] readBytes(InputStream in, int maxLeng) throws IOException 

Method Source Code

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

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

public class Main {
    /** /*from   w  w w.  j  a  v  a 2  s. com*/
     * Reads a number of bytes from a stream.  The specified number of
     * bytes or the whole of the file is read, whichever is shorter.
     *  
     * @param   in  input stream
     * @param   maxLeng  maximum number of bytes to read
     * @return   buffer of bytes containing <tt>maxLeng</tt> bytes
     *           read from <tt>in</tt>, or fewer if the stream ended early
     */
    public static byte[] readBytes(InputStream in, int maxLeng) throws IOException {
        byte[] buf = new byte[maxLeng];
        int pos = 0;
        while (maxLeng - pos > 0) {
            int ngot = in.read(buf, pos, maxLeng - pos);
            if (ngot > 0) {
                pos += ngot;
            } else {
                break;
            }
        }
        if (pos < maxLeng) {
            byte[] buf2 = new byte[pos];
            System.arraycopy(buf, 0, buf2, 0, pos);
            buf = buf2;
        }
        return buf;
    }
}

Related

  1. readBytes(InputStream in, int bufferSize, boolean forceClose)
  2. readBytes(InputStream in, int bytesToRead, byte[] buffer, int bufferOffset)
  3. readBytes(InputStream in, int expectedBytes, long timeoutMs)
  4. readBytes(InputStream in, int len, boolean isLE)
  5. readBytes(InputStream in, int length)
  6. readBytes(InputStream in, long len)
  7. readBytes(InputStream input)
  8. readBytes(InputStream input, byte[] data, int capacity)
  9. readBytes(InputStream input, Class type)