Reads a byte from the InputStream and returns it as a Java byte. - Java java.io

Java examples for java.io:InputStream Read

Description

Reads a byte from the InputStream and returns it as a Java byte.

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 v a2  s  .c  o m*/
     * Reads a byte from the stream and returns it as a Java byte.
     * @param in The input stream
     * @return A byte as a Java byte.
     * @throws IOException If an IO error occurs
     */
    public static byte readByte(final InputStream in) throws IOException {
        byte[] buffer = new byte[1];
        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.get();
    }
}

Related Tutorials