Java File Write via ByteBuffer writeInt(WritableByteChannel channel, int value)

Here you can find the source of writeInt(WritableByteChannel channel, int value)

Description

Writes an integer (32 bit) to the specified byte channel.

License

Open Source License

Parameter

Parameter Description
channel The WritableByteChannel to write to.
value The value to write.

Declaration

public static void writeInt(WritableByteChannel channel, int value) throws IOException 

Method Source Code

//package com.java2s;
// See LICENSE.txt for license information

import java.io.IOException;

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

import java.nio.channels.WritableByteChannel;

public class Main {
    /**/*from w ww  . j  a v  a2 s .co  m*/
     * Writes an integer (32 bit) to the specified byte channel.
     * @param channel The {@link WritableByteChannel} to write to.
     * @param value The value to write.
     */
    public static void writeInt(WritableByteChannel channel, int value) throws IOException {
        ByteBuffer bb4 = getByteBuffer(4);
        bb4.position(0);
        bb4.putInt(value);
        bb4.position(0);
        for (int cnt = 0; cnt < 4;) {
            int n = channel.write(bb4);
            cnt += n;
        }
    }

    /**
     * Writes an integer (32 bit) to specified output stream.
     * @param out The output stream to write to.
     * @param value The value to write.
     * @return The actual number of bytes written.
     */
    public static int writeInt(OutputStream out, int value) throws IOException {
        int res = 0;
        if (out != null) {
            for (int i = 0, shift = 0; i < 4; i++, shift += 8) {
                out.write((value >>> shift) & 0xff);
                res++;
            }
        }
        return res;
    }

    /** Returns a fully initialized empty {@link ByteBuffer} in little endian order. */
    public static ByteBuffer getByteBuffer(int size) {
        return ByteBuffer.allocate(Math.max(0, size)).order(ByteOrder.LITTLE_ENDIAN);
    }

    /** Returns a {@link ByteBuffer} based on {@code buffer} in little endian order. */
    public static ByteBuffer getByteBuffer(byte[] buffer) {
        if (buffer == null) {
            buffer = new byte[0];
        }
        return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN);
    }
}

Related

  1. writeInt(OutputStream os, int val, ByteOrder bo)
  2. writeInt(OutputStream out, ByteOrder order, int i)
  3. writeInt(OutputStream out, int i)
  4. writeInt(WritableByteChannel channel, int val)
  5. writeInt(WritableByteChannel channel, int value)
  6. writeLong(OutputStream in, long i)
  7. writeLong(OutputStream os, Long d)
  8. writeLong(RandomAccessFile raFile, long num)
  9. writeObject(Serializable serializable)