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

Java examples for java.io:InputStream Read

Description

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

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 {
    /**//  ww w.  ja va  2  s.  c o  m
     * Reads a boolean from the stream and returns it as a Java boolean.
     * @param in The input stream
     * @return A boolean as a Java boolean.
     * @throws IOException If an IO error occurs
     */
    public static boolean readBoolean(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() & 0x10000000) > 0;
    }
}

Related Tutorials