Getting different representations from a ByteBuffer : Buffering « File Input Output « Java






Getting different representations from a ByteBuffer

Getting different representations from a ByteBuffer
     

// : c12:GetData.java
// Getting different representations from a ByteBuffer
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.

import java.nio.ByteBuffer;

public class GetData {
  private static final int BSIZE = 1024;

  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.allocate(BSIZE);
    // Allocation automatically zeroes the ByteBuffer:
    int i = 0;
    while (i++ < bb.limit())
      if (bb.get() != 0)
        System.out.println("nonzero");
    System.out.println("i = " + i);
    bb.rewind();
    // Store and read a char array:
    bb.asCharBuffer().put("Howdy!");
    char c;
    while ((c = bb.getChar()) != 0)
      System.out.print(c + " ");
    System.out.println();
    bb.rewind();
    // Store and read a short:
    bb.asShortBuffer().put((short) 471142);
    System.out.println(bb.getShort());
    bb.rewind();
    // Store and read an int:
    bb.asIntBuffer().put(99471142);
    System.out.println(bb.getInt());
    bb.rewind();
    // Store and read a long:
    bb.asLongBuffer().put(99471142);
    System.out.println(bb.getLong());
    bb.rewind();
    // Store and read a float:
    bb.asFloatBuffer().put(99471142);
    System.out.println(bb.getFloat());
    bb.rewind();
    // Store and read a double:
    bb.asDoubleBuffer().put(99471142);
    System.out.println(bb.getDouble());
    bb.rewind();

  }
} ///:~


           
         
    
    
    
    
  








Related examples in the same category

1.Endian differences and data storageEndian differences and data storage
2.View BuffersView Buffers
3.Using BuffersUsing Buffers
4.Output BufferingOutput Buffering
5.Manipulating ints in a ByteBuffer with an IntBufferManipulating ints in a ByteBuffer with an IntBuffer
6.Circular Byte Buffer
7.Circular Char Buffer from http://ostermiller.org
8.Buffered copying
9.Byte Buffer
10.Circular Char Buffer
11.Char Buffer
12.Caching InputStream
13.Caching OutputStream
14.ByteBuffer FloatBuffer demo