Java NIO之Buffer(緩衝區)

​ Java NIO中的緩存區(Buffer)用於和通道(Channel)進行交互。數據是從通道讀入緩衝區,從緩衝區寫入到通道中的。java

​ 緩衝區本質上是一塊能夠寫入數據,而後能夠從中讀取數據的內存。這塊內存被包裝成NIO Buffer對象,並提供了一組方法,用來方便的訪問該塊內存。數組

Buffer底層使用數組實現。緩存


一、NIO 數據讀取基本操做示意

二、Java NIO中Buffer類型

​ Java NIO中,根據數據類型不一樣(boolean 除外),提供了相應類型的緩衝區:app

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer


三、Buffer的基本用法

​ 使用Buffer讀寫數據通常遵循如下四個步驟:this

​ 寫入數據到Buffer;code

​ 調用flip()方法;對象

​ 從Buffer中讀取數據;blog

​ 調用clear()方法或者compact()方法;ip

​ 當向buffer寫入數據時,buffer會記錄下寫了多少數據。一旦要讀取數據,須要經過flip()方法將Buffer從寫模式切換到讀模式。在讀模式下,能夠讀取以前寫入到buffer的全部數據。內存

​ 一旦讀完了全部的數據,就須要清空緩衝區,讓它能夠再次被寫入。有兩種方式能清空緩衝區:調用clear()或compact()方法。clear()方法會清空整個緩衝區。compact()方法只會清除已經讀過的數據。任何未讀的數據都被移到緩衝區的起始處,新寫入的數據將放到緩衝區未讀數據的後面。

String str = "charBuffer";
CharBuffer charBuffer = CharBuffer.allocate(1024);
charBuffer.put(str);
charBuffer.append("--");
charBuffer.append("hello world");

charBuffer.flip();

//單個讀取buffer中的內容
/*while (charBuffer.hasRemaining()) {
    System.out.println(charBuffer.get());
}*/

//一次性讀取buffer中的內容
char[] dst = new char[charBuffer.limit()];
charBuffer.get(dst);
System.out.println(new String(dst));

四、Buffer屬性與方法詳解

4.一、基本屬性
public abstract class Buffer {
    // Invariants: mark <= position <= limit <= capacity
    private int mark = -1;//標記位置 
    private int position = 0;//當前遊標位置
    private int limit;//可讀取數據大小
    private int capacity;//buffer容量大小   
    ...  
}

4.二、經常使用方法
4.2.一、mark()

標記當前位置,配合reset使用。

public final Buffer mark() {
    mark = position;
    return this;
}
4.2.二、reset()

重置遊標爲標記位。

public final Buffer reset() {
    int m = mark;
    if (m < 0)
        throw new InvalidMarkException();
    position = m;
    return this;
}
4.2.三、clear()

清除緩衝區,等待寫入。

public final Buffer clear() {
    position = 0;
    limit = capacity;
    mark = -1;
    return this;
}
4.2.四、flip()

將緩衝區由寫模式切換爲讀模式。

public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
}
4.2.五、rewind()

重置buffer,等待寫入。

public final Buffer rewind() {
    position = 0;
    mark = -1;
    return this;
}
4.2.六、remaining()

獲取剩餘可讀元素個數。

public final int remaining() {
    return limit - position;
}
4.2.七、hasRemaining()

判斷是否還有可讀元素。

public final boolean hasRemaining() {
    return position < limit;
}
相關文章
相關標籤/搜索