參考博客:http://blog.csdn.net/sunzhenhua0608/article/details/31778519
先來一個demo:
import java.nio.ByteBuffer; public class ByteBufferDemo { public static void main(String[] args){ String str = "helloWorld"; ByteBuffer buff = ByteBuffer.wrap(str.getBytes()); System.out.println("position:"+buff.position()+"\t limit:"+buff.limit()); //讀取兩個字節 byte[] abytes = new byte[1]; buff.get(abytes); System.out.println("get one byte to string:" + new String(abytes)); //Reads the byte at this buffer's current position, and then increments the position. buff.get(); System.out.println("獲取兩個字節(兩次get()方法調用)后"); System.out.println("position:"+buff.position()+"\t limit:"+buff.limit()); //Sets this buffer's mark at its position. like ByteBuffer.this.mark=position buff.mark(); System.out.println("mark()..."); System.out.println("position:"+buff.position()+"\t limit:"+buff.limit()); //當讀取到碼流后,進行解碼。首先對ByteBuffer進行flip操作, //它的作用是將緩沖區當前的limit設置為position,position設置為0 //flip方法將Buffer從寫模式切換到讀模式。調用flip()方法會將position設回0,並將limit設置成之前position的值。
// 這里的flip()方法,在詳細的描述一下,其事這里是理解position和limit這兩個屬性的關鍵。
//用於后續對緩沖區的讀取操作。然后根據緩沖區可讀的字節個數創建字節數組,
//調用ByteBuffer的get操作將緩沖區可讀的字節(獲取position到limit的字節)
//數組復制到新創建的字節數組中,最后調用字符串的構造函數創建請求消息體並打印。 buff.flip(); System.out.println("flip()..."); System.out.println("position:"+buff.position()+"\t limit:"+buff.limit()); byte[] tbyte = new byte[1]; buff.get(tbyte); System.out.println("get one byte to string:" + new String(tbyte)); System.out.println("position:"+buff.position()+"\t limit:"+buff.limit()); //BufferUnderflowException 測試 // byte[] trbyte = new byte[2]; // buff.get(trbyte); } }
輸出: