Java I/O How to - Store and read an int/long/float/double via ByteBuffer








Question

We would like to know how to store and read an int/long/float/double via ByteBuffer.

Answer

import java.nio.ByteBuffer;
/*ww w. jav a2  s  . com*/
public class Main {
  private static final int BSIZE = 1024;

  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.allocate(BSIZE);
    bb.asIntBuffer().put(99471142);
    System.out.println(bb.getInt());

    bb = ByteBuffer.allocate(BSIZE);
    bb.asLongBuffer().put(99472342341142L);
    System.out.println(bb.getLong());

    bb = ByteBuffer.allocate(BSIZE);

    bb.asFloatBuffer().put(99471142);
    System.out.println(bb.getFloat());

    bb = ByteBuffer.allocate(BSIZE);

    bb.asDoubleBuffer().put(99471142);
    System.out.println(bb.getDouble());

  }
}

The code above generates the following result.