read Long Array from InputStream - Java java.io

Java examples for java.io:InputStream Read

Description

read Long Array from InputStream

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static long[] readLongArray(InputStream in, int size)
            throws IOException {
        long[] longs = new long[size];

        for (int i = 0; i < size; i++) {
            longs[i] = readLong(in);//  w  w w .  ja  v  a2 s. c om
        }

        return longs;
    }

    public static long readLong(InputStream in) throws IOException {

        return bytesToLong(readBytes(in, 8));
    }

    public final static long bytesToLong(byte[] bytes) {
        if (bytes == null || bytes.length != 8)
            throw new IllegalArgumentException("byte array size must be 8!");

        long i = 0;

        i = ((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF);
        i = (i << 8) | (bytes[2] & 0xFF);
        i = (i << 8) | (bytes[3] & 0xFF);
        i = (i << 8) | (bytes[4] & 0xFF);
        i = (i << 8) | (bytes[5] & 0xFF);
        i = (i << 8) | (bytes[6] & 0xFF);
        i = (i << 8) | (bytes[7] & 0xFF);
        // i = (i << 8) | (bytes [3] & 0xFF) ;
        return i;
    }

    public final static byte[] readBytes(InputStream in, int size)
            throws IOException {
        if (size <= 0)
            return new byte[0];

        byte[] buffer = new byte[size];

        int count = 0;
        int ret = 0;
        while (true) {
            ret = in.read(buffer, count, size - count);
            if (ret == -1)
                throw new IOException("No more bytes! [" + count + " < "
                        + size + "]");
            count += ret;
            if (count == size)
                break;

        }
        if (count != size)
            throw new IOException("Must be " + size + " bytes! [" + count
                    + "]");

        return buffer;
    }
}

Related Tutorials