Writes an Int32 to the OutputStream - Java java.io

Java examples for java.io:OutputStream

Description

Writes an Int32 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  ww w. ja v  a  2s.com
     * Writes an Int32 to the stream
     * @param out The output stream
     * @param value The int to write.  Will be written as a .NET Int32.
     * @throws IOException If an IO error occurs
     */
    public static void writeInt32(final OutputStream out, int value)
            throws IOException {
        byte[] buffer = new byte[4];
        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.putInt(value); //Write the int to the buffer

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

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

Related Tutorials