September 19, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

The ByteBuffer Class in Java

  • August 20, 2002
  • By Richard G. Baldwin
  • Send Email »
  • More Articles »

Run the Program

If you haven't already done so, I encourage you to copy the code from Listing 37 into your text editor, compile it, and execute it.  Experiment with it, making changes, and observing the results of your changes.

Remember, however, that you must be running Java version 1.4.0 or later to compile and execute this program.

Complete Program Listing

Complete listings of the programs discussed in this lesson are shown in Listing 37 and 38 below.
 
/* File ByteBuffer01.java
Copyright 2002, R.G.Baldwin

Illustrates most of the features of
the ByteBuffer class.

Tested using JDK 1.4.0 under Win 2000.

The output is:

Create and populate array
Show array data
0 1 2 3 4 5 6 7

Wrap byte array in buffer
Buffer is direct: false
Buffer data for buf1
0 1 2 3 4 5 6 7

Modify first array element
Show array data
10 1 2 3 4 5 6 7
Buffer data for buf1
10 1 2 3 4 5 6 7

Modify the buffer
Buffer data for buf1
10 1 2 20 21 22 6 7
Show array data
10 1 2 20 21 22 6 7

Get absolute
Element 3 = 20
Element 5 = 22
Element 7 = 7

Contiguous get
Buffer data for buf1
10 1 2 20 21 22 6 7
Show array data
0 0 0 0 0 0 0 0 0 0
Show array data
0 0 0 1 2 20 21 22 0 0

Contiguous put from array
Show array data
0 0 0 1 2 20 21 22 0 0
Buffer data for buf1
0 0 1 2 20 21 22 0

Contiguous put from buffer
Buffer is direct: false
Buffer data for buf2
0 0 0 0 0 0 0 0 0 0
Buffer data for buf1
0 0 1 2 20 21 22 0
Buffer data for buf2
0 0 0 1 2 20 21 22 0 0
Show array data
0 0 0 1 2 20 21 22 0 0

Compacting
Buffer data for buf2
22 0 0
Buffer data for buf2
1 2 20 21 22 0 0 22 0 0

Duplicating
Buffer data for buf2
1 2 20 21 22 0 0 22 0 0
Buffer data for buf3
1 2 20 21 22 0 0 22 0 0
Buffer data for buf2
1 2 20 21 22 0 0 99 0 0
Buffer data for buf3
1 2 20 21 22 0 0 99 0 0

Slice
Buffer data for buf2
1 2 20 21 22 0 0 99 0 0
Buffer data for buf4
21 22 0 0 99 0 0
Buffer data for buf2
1 2 20 21 22 0 0 99 66 0
Buffer data for buf4
21 22 0 0 99 66 0

Other primitive types
Buffer is direct: true
Order = BIG_ENDIAN
Buffer data for buf5
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0
0
No backing array
Put and get primitive types
Put a double relative
position = 8
Put a float relative
position = 12
Put a long relative
position = 20

Get double relative
0.3333333333333333
position = 8
Get float relative
0.16666667
position = 12
Get long relative
9223372036854775807
position = 20

Get float absolute
0.16666667
position = 20

Put int absolute
Get int absolute
2147483647
position = 20

Work with views
Clear buf5
Buffer Properties for buf5
  capacity=25 limit=25 position=0
Raw byte data
Buffer data for buf5
0 0 0 1 0 0 0 2 0 0 0 4
0 0 0 8 0 0 0 16 0 0 0 32
0

This won't always work

More complex approach
1 2 4 8 16 32

Get a view
Buffer Properties for buf6
  capacity=6 limit=6 position=0
Read-only = false

Get relative from view
1 2 4 8 16 32
Get absolute from view
Element 4 = 16

Put absolute in view
Show modified view
1 2 4 8 99 32
Show backing buffer
Buffer data for buf5
0 0 0 1 0 0 0 2 0 0 0 4
0 0 0 8 0 0 0 99 0 0 0 32
0

Create read-only view
Read-only = true
Show backing buffer
Buffer data for buf5
0 0 0 1 0 0 0 2 0 0 0 4
0 0 0 8 0 0 0 99 0 0 0 32
0
Show view data
Buffer data for buf7
0 0 0 1 0 0 0 2 0 0 0 4
0 0 0 8 0 0 0 99 0 0 0 32
0

Modify backing buffer
Show backing buffer
Buffer data for buf5
66 0 0 1 0 0 0 2 0 0 0 4
0 0 0 8 0 0 0 99 0 0 0 32
0
Show view data
Buffer data for buf7
66 0 0 1 0 0 0 2 0 0 0 4
0 0 0 8 0 0 0 99 0 0 0 32
0

Modify view oops!

**************************************/

import java.nio.*;

class ByteBuffer01{
  static void showBufferProperties(
               Buffer buf,String name){
    System.out.println(
       "Buffer Properties for " + name
                    +"\n  capacity=" 
                    + buf.capacity()
                    + " limit=" 
                    + buf.limit()
                    + " position=" 
                    + buf.position());
  }//end showBufferProperties
  //---------------------------------//
  
  static void showBufferData(
          ByteBuffer buf, String name){
    //Displays buffer contents from 
    // current position to limit using
    // relative get method, twelve 
    // elements per row.
    System.out.println(
            "Buffer data for " + name);
    int cnt = 0;
    while(buf.hasRemaining()){
      System.out.print(
                      buf.get() + " ");
      cnt++;
      if(cnt%12 == 0)
            System.out.println();//line
    }//end while loop
    System.out.println();//blank line
  }//end showBufferData
  //---------------------------------//

  static void showArrayData(
                         byte[] array){
    System.out.println(
                    "Show array data");
    for(int cnt = 0; 
            cnt < array.length; cnt++){
      System.out.print(
                     array[cnt] + " ");
      if((cnt+1)%12 == 0)
            System.out.println();//line
    }//end for loop
    System.out.println();//blank line
  }//end showArrayData
  //---------------------------------//
    
  public static void main(
                        String[] args){
    
    //Wrap a byte array into a buffer
    System.out.println(
          "Create and populate array");
    byte[] a1 = {0,1,2,3,4,5,6,7};
    showArrayData(a1);
    System.out.println();//blank line
    
    System.out.println(
          "Wrap byte array in buffer");
    ByteBuffer buf1 = 
                ByteBuffer.wrap(a1);
    System.out.println(
                  "Buffer is direct: " 
                   + buf1.isDirect());
    showBufferData(buf1, "buf1");
    System.out.println();//blank line
        
    //Mods to the buffer will cause the
    // array to be modified and vice 
    // versa.
    System.out.println(
         "Modify first array element");
    a1[0] = 10;
    showArrayData(a1);
    buf1.position(0);
    showBufferData(buf1, "buf1");
    System.out.println();//blank line
    
    System.out.println(
                  "Modify the buffer");
    buf1.put(3,(byte)20);
    buf1.position(4);
    buf1.put((byte)21);
    buf1.put((byte)22);
    buf1.position(0);
    showBufferData(buf1, "buf1");
    showArrayData(a1);
    System.out.println();//blank line
    
    System.out.println("Get absolute");
    System.out.println("Element 3 = " 
                        + buf1.get(3));
    System.out.println("Element 5 = " 
                        + buf1.get(5));
    System.out.println("Element 7 = " 
                        + buf1.get(7));
    System.out.println();//blank line
    
    System.out.println(
                     "Contiguous get");
    buf1.position(0);
    showBufferData(buf1, "buf1");
    byte[] a2 = new byte[10];
    showArrayData(a2);
    buf1.position(1);
    buf1.get(a2, 3, 5);
    showArrayData(a2);
    System.out.println();//blank line
    
    System.out.println(
          "Contiguous put from array");
    showArrayData(a2);
    buf1.position(0);
    buf1.put(a2, 1, 8);
    buf1.position(0);
    showBufferData(buf1, "buf1");
    System.out.println();//blank line
    
    System.out.println(
         "Contiguous put from buffer");
    ByteBuffer buf2 = 
               ByteBuffer.allocate(10);
    System.out.println(
                   "Buffer is direct: "
                    + buf2.isDirect());
    showBufferData(buf2, "buf2");
    buf2.position(1);

    buf1.position(0);
    buf2.put(buf1);
    buf1.position(0);
    showBufferData(buf1, "buf1");
    buf2.position(0);
    showBufferData(buf2, "buf2");
    if(buf2.hasArray())
      showArrayData(buf2.array());
    System.out.println();//blank line
      
    System.out.println("Compacting");
    buf2.position(3);
    buf2.compact();
    showBufferData(buf2, "buf2");
    buf2.position(0);
    showBufferData(buf2, "buf2");
    System.out.println();//blank line
    
    System.out.println("Duplicating");
    ByteBuffer buf3 = buf2.duplicate();
    buf2.position(0);
    showBufferData(buf2, "buf2");
    buf3.position(0);
    showBufferData(buf3, "buf3");
    buf3.put(7,(byte)99);
    buf2.position(0);
    showBufferData(buf2, "buf2");
    buf3.position(0);
    showBufferData(buf3, "buf3");
    System.out.println();//blank line
    
    System.out.println("Slice");
    buf2.position(3);
    ByteBuffer buf4 = buf2.slice();
    buf2.position(0);
    showBufferData(buf2, "buf2");
    buf4.position(0);
    showBufferData(buf4, "buf4");
    buf4.put(5,(byte)66);
    buf2.position(0);
    showBufferData(buf2, "buf2");
    buf4.position(0);
    showBufferData(buf4, "buf4");
    System.out.println();//blank line
    
    //The above operations are common
    // to most of the subclasses of
    // Buffer.  The following 
    // operations are specific to
    // ByteBuffer.
    
    System.out.println(
              "Other primitive types");
    ByteBuffer buf5 = 
         ByteBuffer.allocateDirect(25);
    System.out.println(
                   "Buffer is direct: "
                    + buf5.isDirect());
    System.out.println("Order = " 
                       + buf5.order());
    showBufferData(buf5, "buf5");
    if(buf5.hasArray())
      showArrayData(buf5.array());
    else System.out.println(
                   "No backing array");
    
    buf5.position(0);
    System.out.println(
        "Put and get primitive types");
    System.out.println(
              "Put a double relative");
    buf5.putDouble(1.0/3.0);
    System.out.println("position = " 
                    + buf5.position());
    System.out.println(
               "Put a float relative");
    buf5.putFloat((float)(1.0/6.0));
    System.out.println("position = " 
                    + buf5.position());
    System.out.println(
                "Put a long relative");
    buf5.putLong(Long.MAX_VALUE);
    System.out.println("position = " 
                    + buf5.position());
    System.out.println();//blank line
    
    buf5.position(0);
    System.out.println(
                "Get double relative");
    System.out.println(
                     buf5.getDouble());
    System.out.println("position = " 
                    + buf5.position());
    System.out.println(
                 "Get float relative");
    System.out.println(
                      buf5.getFloat());
    System.out.println("position = " 
                    + buf5.position());
    System.out.println(
                  "Get long relative");
    System.out.println(buf5.getLong());
    System.out.println("position = " 
                    + buf5.position());
    System.out.println();//blank line
    
    System.out.println(
                 "Get float absolute");
    System.out.println(
                     buf5.getFloat(8));
    System.out.println("position = " 
                    + buf5.position());
    System.out.println();//blank line
    
    System.out.println(
                   "Put int absolute");
    buf5.putInt(20,Integer.MAX_VALUE);
    System.out.println(
                   "Get int absolute");
    System.out.println(
                      buf5.getInt(20));
    System.out.println("position = " 
                    + buf5.position());
    System.out.println();//blank line
    
    System.out.println(
                    "Work with views");
    System.out.println("Clear buf5");
    buf5.clear();
    showBufferProperties(buf5, "buf5");
    buf5.putInt((int)1);
    buf5.putInt((int)2);
    buf5.putInt((int)4);
    buf5.putInt((int)8);
    buf5.putInt((int)16);
    buf5.putInt((int)32);
    buf5.position(0);
    System.out.println(
                      "Raw byte data");
    showBufferData(buf5, "buf5");
    System.out.println();//blank line
    
    System.out.println(
             "This won't always work");
    //The following works only if the
    // size of the buffer is a 
    // multiple of the number of bytes
    // for the type.
    buf5.position(0);
/*
    showBufferProperties(buf5, "buf5");
    while(buf5.hasRemaining()){
      System.out.print(
                  buf5.getInt() + " ");
    }//end while loop
*/
    System.out.println();//blank line
    
    System.out.println(
              "More complex approach");
    int cnt = 0;
    while(cnt < buf5.limit()-4){
      System.out.print(
               buf5.getInt(cnt) + " ");
      cnt += 4;
    }//end while loop
    System.out.println();//blank line
    System.out.println();//blank line

    System.out.println("Get a view");
    buf5.position(0);
    IntBuffer buf6 = 
                    buf5.asIntBuffer();
    showBufferProperties(buf6, "buf6");
    System.out.println("Read-only = " 
                  + buf6.isReadOnly());
    System.out.println();//blank line 
    
    System.out.println(
             "Get relative from view");
    while(buf6.hasRemaining()){
      System.out.print(
                     buf6.get() + " ");
    }//end while loop
    System.out.println();//blank line

    System.out.println(
             "Get absolute from view");
    System.out.println("Element 4 = " 
                        + buf6.get(4));
    System.out.println();//blank line
    
    System.out.println(
               "Put absolute in view");
    buf6.put(4,99);
    buf6.position(0);
    System.out.println(
                 "Show modified view");
    while(buf6.hasRemaining()){
      System.out.print(
                     buf6.get() + " ");
    }//end while loop
    System.out.println();//blank line

    System.out.println(
                "Show backing buffer");
    buf5.position(0);
    showBufferData(buf5, "buf5");

    System.out.println();//blank line
    
    System.out.println(
              "Create read-only view");
    buf5.position(0);
    ByteBuffer buf7 = 
               buf5.asReadOnlyBuffer();
    System.out.println("Read-only = " 
                  + buf7.isReadOnly());
    
    System.out.println(
                "Show backing buffer");
    showBufferData(buf5, "buf5");
    System.out.println(
                     "Show view data");
    showBufferData(buf7, "buf7");
    System.out.println();//blank line
    
    System.out.println(
              "Modify backing buffer");
    buf5.put(0,(byte)66);
    System.out.println(
                "Show backing buffer");
    buf5.position(0);
    showBufferData(buf5, "buf5");
    System.out.println(
                     "Show view data");
    buf7.position(0);
    showBufferData(buf7, "buf7");
    System.out.println();//blank line

    System.out.println(
                  "Modify view oops!");
    //Following statement throws 
    // exception
    //buf7.put(0,(byte)66);
  
  }// end main

}//end class ByteBuffer01 definition

Listing 37

 
 
/* File ByteBuffer02.java
Copyright 2002, R.G.Baldwin

Illustrates lack of type safety when
using views of a ByteBuffer object.

Creates a ByteBuffer object having 17
elements.

Populates the buffer with two double
values.

Displays the individual bytes in the
buffer.

Views the buffer as type double.

Views the buffer as type int.

Tested using JDK 1.4.0 under Win 2000.

The output is:
  
Show empty byte buffer
Buffer data for buf1
0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 
0 
Populate with double values
Show populated buffer as bytes
Buffer data for buf1
63 -16 0 0 0 0 0 0 
64 0 0 0 0 0 0 0 
0 
View buffer as type double
1.0 2.0 
View buffer as type int
1072693248 0 1073741824 0
**************************************/

import java.nio.*;

class ByteBuffer02{
  
  static void showBufferData(
          ByteBuffer buf, String name){
    //Displays byte buffer contents
    // eight bytes per row.
    
    //Save position
    int pos = buf.position();
    //Set position to zero
    buf.position(0);
    System.out.println(
            "Buffer data for " + name);
    int cnt = 0;
    while(buf.hasRemaining()){
      System.out.print(
                      buf.get() + " ");
      cnt++;
      if(cnt%8 == 0)//start new row
            System.out.println();
    }//end while loop
    System.out.println();//new line
    //Restore position and return
    buf.position(pos);
  }//end showBufferData
  //---------------------------------//
    
  public static void main(
                        String[] args){
    
    ByteBuffer buf1 = 
               ByteBuffer.allocate(17);
    System.out.println(
             "Show empty byte buffer");
    showBufferData(buf1,"buf1");
    System.out.println(
        "Populate with double values");
    buf1.putDouble(1.0);
    buf1.putDouble(2.0);
    System.out.println(
     "Show populated buffer as bytes");
    showBufferData(buf1,"buf1");
    
    System.out.println(
         "View buffer as type double");
    buf1.position(0);
    DoubleBuffer buf2 = //view object
                 buf1.asDoubleBuffer();
    while(buf2.hasRemaining()){
      System.out.print(
                     buf2.get() + " ");
    }//end while loop
    System.out.println();//blank line
    
    System.out.println(
            "View buffer as type int");
    IntBuffer buf3 = //view object
                    buf1.asIntBuffer();
    while(buf3.hasRemaining()){
      System.out.print(
                     buf3.get() + " ");
    }//end while loop
    System.out.println();//blank line
  }// end main

}//end class ByteBuffer02 definition

Listing 38


Copyright 2002, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects, and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which has gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin@DickBaldwin.com

-end-
 



Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel