Java InputStream Read Bytes readBytes(InputStream inputStream, int length)

Here you can find the source of readBytes(InputStream inputStream, int length)

Description

read Bytes

License

Apache License

Declaration

public static byte[] readBytes(InputStream inputStream, int length) throws IOException 

Method Source Code

//package com.java2s;
/** Copyright 2013 BlackBerry, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. /*from  w w  w .j  av a  2  s .  c o m*/
 */

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

public class Main {
    public static byte[] readBytes(InputStream inputStream) throws IOException {
        int length = readInt(inputStream);
        return readBytes(inputStream, length);
    }

    public static byte[] readBytes(InputStream inputStream, int length) throws IOException {
        byte[] buffer = new byte[length];
        int bytesRead = 0;
        int limit = 0;
        while (limit < length && bytesRead != -1) {
            bytesRead = inputStream.read(buffer, limit, length - limit);
            limit += bytesRead;
        }
        if (limit < length) {
            throw new IOException("Not enough bytes to read.");
        }
        return buffer;
    }

    public static int readInt(InputStream inputStream) throws IOException {
        int value = 0;
        int i = 0;
        long b;
        while (((b = inputStream.read()) & 0x80L) != 0) {
            value |= (b & 0x7F) << i;
            i += 7;
            if (i >= 7 * 5) {
                throw new IOException("Didn't reach the end of the varint after 5 bytes.");
            }
        }
        value |= b << i;

        // un-zig-zag it
        int temp = (((value << 31) >> 31) ^ value) >> 1;
        // since we lost that first bit during all that zigging and zagging,
        // make sure it's the right one now
        value = temp ^ (value & (1 << 31));

        return value;
    }
}

Related

  1. readBytes(InputStream inputStream)
  2. readBytes(InputStream inputStream)
  3. readBytes(InputStream inputStream, boolean close)
  4. readBytes(InputStream inputStream, byte[] buffer, int offset, int length)
  5. readBytes(InputStream inputStream, int bufSize)
  6. readBytes(InputStream inputStream, int numberOfBytes)
  7. readBytes(InputStream inputStream, int numberOfBytes)
  8. readBytes(InputStream ins, byte[] buf, int size)
  9. readBytes(InputStream is)