標籤:需要 sys 緩衝 nio [] 大小 通過 數組 import
import java.nio.ByteBuffer ;
public class ByteBufferDemo01{
public static void main(String args[]){
ByteBuffer buf = ByteBuffer.allocateDirect(10) ; // 準備出10個大小的緩衝區
byte temp[] = {1,3,5,7,9} ; // 設定內容
buf.put(temp) ; // 設定一組內容
buf.flip() ;
System.out.print("主要緩衝區中的內容:") ;
while(buf.hasRemaining()){
int x = buf.get() ;
System.out.print(x + "、") ;
}
}
}
//***
import java.nio.IntBuffer ;
public class IntBufferDemo01{
public static void main(String args[]){
IntBuffer buf = IntBuffer.allocate(10) ; // 準備出10個大小的緩衝區
System.out.print("1、寫入資料之前的position、limit和capacity:") ;
System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " + buf.capacity()) ;
int temp[] = {5,7,9} ;// 定義一個int數組
buf.put(3) ; // 設定一個資料
buf.put(temp) ; // 此時已經存放了四個記錄
System.out.print("2、寫入資料之後的position、limit和capacity:") ;
System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " + buf.capacity()) ;
buf.flip() ; // 重設緩衝區
// postion = 0 ,limit = 原本position
System.out.print("3、準備輸出資料時的position、limit和capacity:") ;
System.out.println("position = " + buf.position() + ",limit = " + buf.limit() + ",capacty = " + buf.capacity()) ;
System.out.print("緩衝區中的內容:") ;
while(buf.hasRemaining()){
int x = buf.get() ;
System.out.print(x + "、") ;
}
}
}//***
import java.nio.IntBuffer ;
public class IntBufferDemo02{
public static void main(String args[]){
IntBuffer buf = IntBuffer.allocate(10) ; // 準備出10個大小的緩衝區
IntBuffer sub = null ; // 定義子緩衝區
for(int i=0;i<10;i++){
buf.put(2 * i + 1) ; // 在主要緩衝區中加入10個奇數
}
// 需要通過slice() 建立子緩衝區
buf.position(2) ;
buf.limit(6) ;
sub = buf.slice() ;
for(int i=0;i<sub.capacity();i++){
int temp = sub.get(i) ;
sub.put(temp-1) ;
}
buf.flip() ; // 重設緩衝區
buf.limit(buf.capacity()) ;
System.out.print("主要緩衝區中的內容:") ;
while(buf.hasRemaining()){
int x = buf.get() ;
System.out.print(x + "、") ;
}
}
}//****************************
import java.nio.IntBuffer ;
public class IntBufferDemo03{
public static void main(String args[]){
IntBuffer buf = IntBuffer.allocate(10) ; // 準備出10個大小的緩衝區
IntBuffer read = null ; // 定義子緩衝區
for(int i=0;i<10;i++){
buf.put(2 * i + 1) ; // 在主要緩衝區中加入10個奇數
}
read = buf.asReadOnlyBuffer() ;// 建立唯讀緩衝區
read.flip() ; // 重設緩衝區
System.out.print("主要緩衝區中的內容:") ;
while(read.hasRemaining()){
int x = read.get() ;
System.out.print(x + "、") ;
}
read.put(30) ; // 修改,錯誤
}
}
Java新IO】_緩衝區與Buffer\代碼