Buffer中常用(必用)的幾個方法介紹
首先介紹一下Buffer的使用場景,Buffer是Java NIO中非常重要的一個類,數(shù)據(jù)在各種Channel的讀寫時都需要這個類來緩沖。然而Buffer在讀寫之前需要做一些準(zhǔn)備工作,比如:在讀取Buffer里的數(shù)據(jù)之前要先在Buffer里準(zhǔn)備好要讀取數(shù)據(jù),往Buffer里寫數(shù)據(jù)時,要找出Buffer里的空余空間或者要清空Buffer等等。做以上事情方法有:clear(), flip(), rewind().因為我經(jīng)常記不住這幾個方法的功能,所以在此記錄一下, 也供他人查找。
Buffer有幾個下標(biāo)需要注意:position(當(dāng)前位置), limit(可度/寫數(shù)據(jù) 下標(biāo)的最大值), capacity(實際空間)
1.clear()
使Buffer為一系列新的通道讀取或相對放置 操作做好準(zhǔn)備,即為往Buffer中寫數(shù)據(jù)做好準(zhǔn)備
public final Buffer clear()
{
this.position = 0;
this.limit = this.capacity;
this.mark = -1;
return this;
}
{
this.position = 0;
this.limit = this.capacity;
this.mark = -1;
return this;
}
2. flip()
使Buffer為一系列新的通道寫入或相對獲取 操作做好準(zhǔn)備:它將限制設(shè)置為當(dāng)前位置,然后將位置設(shè)置為 0。即為從Buffer中度數(shù)據(jù)做好準(zhǔn)備
public final Buffer flip()
{
this.limit = this.position;
this.position = 0;
this.mark = -1;
return this;
}
3.rewind(){
this.limit = this.position;
this.position = 0;
this.mark = -1;
return this;
}
使緩沖區(qū)為重新讀取已包含的數(shù)據(jù)做好準(zhǔn)備:它使限制保持不變,將位置設(shè)置為 0。
public final Buffer rewind()
{
this.position = 0;
this.mark = -1;
return this;
}
{
this.position = 0;
this.mark = -1;
return this;
}
Kyle Wang
posted on 2012-07-21 15:07 王樹東 閱讀(225) 評論(0) 編輯 收藏 所屬分類: Java Skills Learning and Sharing