Writes a boolean to the OutputStream - Java java.io

Java examples for java.io:OutputStream

Description

Writes a boolean to the OutputStream

Demo Code


//package com.java2s;

import java.io.IOException;

import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    /**//from w w w.j  a va2 s. c  o  m
     * Writes a boolean to the stream
     * @param out The output stream
     * @param value The boolean to write.  Will be written as a .NET boolean.
     * @throws IOException If an IO error occurs
     */
    public static void writeBoolean(final OutputStream out, boolean value)
            throws IOException {
        byte[] buffer = new byte[1];
        ByteBuffer bb = ByteBuffer.wrap(buffer);

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

        bb.put((byte) (value ? 0b10000000 : 0)); //Write the byte to the buffer

        out.write(buffer); //Write the buffer to the stream
    }
}

Related Tutorials