Reads an Int64 from the InputStream and returns it as a Java long. - Java java.io

Java examples for java.io:InputStream Read

Description

Reads an Int64 from the InputStream and returns it as a Java long.

Demo Code


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

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    /**//from w  w  w  .j  a  va  2 s  .co m
     * Reads an Int64 from the stream and returns it as a Java long.
     * @param in The input stream
     * @return An Int64 as a Java long.
     * @throws IOException If an IO error occurs
     */
    public static long readInt64(final InputStream in) throws IOException {
        byte[] buffer = new byte[8];
        ByteBuffer bb = ByteBuffer.wrap(buffer);

        if (in.read(buffer) < 0) //Read the stream into the buffer
            throw new EOFException();

        //Switch the byte ordering to little endian, which is what .NET uses
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.position(0);

        return bb.getLong();
    }
}

Related Tutorials