Java InputStream Read Bytes readBytes(InputStream in, int len, boolean isLE)

Here you can find the source of readBytes(InputStream in, int len, boolean isLE)

Description

Read bytes from input stream.

License

Apache License

Parameter

Parameter Description
in Input stream.
len Bytes length.
isLE Whether it's little-endian

Exception

Parameter Description
IOException an exception

Return

Bytes arrays.

Declaration

public static byte[] readBytes(InputStream in, int len, boolean isLE) throws IOException 

Method Source Code

//package com.java2s;
/**/*from ww  w  .  j av a  2  s.  c o m*/
 * 
 *Copyright 2014 The Darks Codec Project (Liu lihua)
 *
 *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.
 */

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

public class Main {
    /**
     * Read bytes from input stream.
     * 
     * @param in Input stream.
     * @param len Bytes length.
     * @param isLE Whether it's little-endian
     * @return Bytes arrays.
     * @throws IOException
     */
    public static byte[] readBytes(InputStream in, int len, boolean isLE) throws IOException {
        if (len == 0) {
            return new byte[0];
        }
        byte[] bytes = new byte[len];
        int rlen = in.read(bytes);
        if (rlen != len) {
            throw new IOException("readBytes length is not match." + len + " which is " + rlen);
        }
        if (isLE) {
            bytes = reverseBytes(bytes);
        }
        return bytes;
    }

    public static byte[] reverseBytes(byte[] bytes) {
        int size = bytes.length;
        int len = size / 2;
        int max = size - 1;
        for (int i = 0; i < len; i++) {
            bytes[i] ^= bytes[max - i];
            bytes[max - i] ^= bytes[i];
            bytes[i] ^= bytes[max - i];
        }
        return bytes;
    }
}

Related

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