read Double from InputStream - Java java.io

Java examples for java.io:InputStream Read

Description

read Double from InputStream

Demo Code


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

public class Main {
    public static double readDouble(InputStream in) throws IOException {

        return bytesToDouble(readBytes(in, 8));
    }/*from   w  w w. j  av a  2s . c  o  m*/

    public final static double bytesToDouble(byte[] bytes) {
        return Double.longBitsToDouble(bytesToLong(bytes));
    }

    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;
    }

    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;
    }
}

Related Tutorials