There are two ways to write data to a buffer:
Method | Meaning |
---|---|
put(int index, byte b) | writes the specified b data at the specified index. The call to this method does not change the current position of the buffer. |
put(byte b) | a relative put() method that writes the specified byte at the current position of the buffer and increments the position by 1. |
put(byte[] source, int offset, int length) | reads the length number of bytes from the source array starting at offset and writes them to the buffer starting at the current position. The position of the buffer is incremented by length. |
put(byte[] source) | the same as calling put(byte[] source, 0, source.length). |
ByteBuffer put(ByteBuffer src) | reads the remaining bytes from the specified byte buffer src and writes them to the buffer. |
import java.nio.ByteBuffer; public class Main { public static void main(String[] args) { // Create a byte buffer with a capacity of 8 ByteBuffer bb = ByteBuffer.allocate(8); // Print the buffer info System.out.println("After creation:"); printBufferInfo(bb);//from ww w. j a va 2 s . c om // Populate buffer elements from 50 to 57 for (int i = 50; i < 58; i++) { bb.put((byte) i); } // Print the buffer info System.out.println("After populating data:"); printBufferInfo(bb); } public static void printBufferInfo(ByteBuffer bb) { int limit = bb.limit(); System.out.println("Position = " + bb.position() + ", Limit = " + limit); // Use absolute reading without affecting the position System.out.print("Data: "); for (int i = 0; i < limit; i++) { System.out.print(bb.get(i) + " "); } System.out.println(); } }
You can read/write data using the relative get() and put() methods if the position of the buffer is less than its limit.
The working range for the absolute read/write is the index between zero and limit -1. So