Reads an Int32 from the InputStream and returns it as a Java int. - Java java.io

Java examples for java.io:InputStream Read

Description

Reads an Int32 from the InputStream and returns it as a Java int.

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 www  .j a v a 2s  . co  m
     * Reads an Int32 from the stream and returns it as a Java int.
     * @param in The input stream
     * @return An Int32 as a Java int.
     * @throws IOException If an IO error occurs
     */
    public static int readInt32(final InputStream in) throws IOException {
        byte[] buffer = new byte[4];
        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);

        //System.out.println("Int32:");
        //printBytes(buffer);

        return bb.getInt();
    }
}

Related Tutorials