Java——新IO 缓冲区与Buffer

时间:2023-03-09 19:11:20
Java——新IO 缓冲区与Buffer

Java——新IO 缓冲区与Buffer

缓冲区和Buffer

Java——新IO 缓冲区与Buffer

Java——新IO 缓冲区与Buffer

import java.nio.IntBuffer;

//=================================================
// File Name : IntBuffer_demo
//------------------------------------------------------------------------------
// Author : Common //主类
//Function : IntBuffer_demo
public class IntBuffer_demo { public static void main(String[] args) {
// TODO 自动生成的方法存根
IntBuffer buf = IntBuffer.allocate(10); //开辟10个大小的缓冲区
System.out.print("1.写入数据之前的position、limit和capacity");
System.out.println("position="+buf.position()+"、limit="+buf.limit()+"、capacity="+buf.capacity());
int temp[] = {3,5,7}; //定义整型数组
buf.put(3); //向缓冲区写入数据
buf.put(temp); //向缓冲区中写入一组数据
System.out.print("2.写入数据之后的position、limit和capacity");
System.out.println("position="+buf.position()+"、limit="+buf.limit()+"、capacity="+buf.capacity());
buf.flip(); //重设缓冲区,改变指针
System.out.print("3.准备输出数据时的position、limit和capacity");
System.out.println("position="+buf.position()+"、limit="+buf.limit()+"、capacity="+buf.capacity());
while(buf.hasRemaining()){
int x = buf.get();
System.out.print(x+"、");
}
} }

Java——新IO 缓冲区与Buffer

Java——新IO 缓冲区与Buffer

Java——新IO 缓冲区与Buffer

创建子缓冲区

import java.nio.IntBuffer;

//=================================================
// File Name : IntBuffer_demo
//------------------------------------------------------------------------------
// Author : Common //主类
//Function : IntBuffer_demo
public class IntBuffer_demo { public static void main(String[] args) {
// TODO 自动生成的方法存根 IntBuffer buf = IntBuffer.allocate(10); //开辟10个大小的缓冲区
IntBuffer sub = null; //定义缓冲区对象
for(int i=0;i<10;i++){
buf.put(2*i+1);
}
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()); //设置limit
System.out.println("主缓冲区中的内容:");
while(buf.hasRemaining()){
int x = buf.get(); //取出当前内容
System.out.print(x+"、");
}
} }

Java——新IO 缓冲区与Buffer

Java——新IO 缓冲区与Buffer

import java.nio.IntBuffer;

//=================================================
// File Name : IntBuffer_demo
//------------------------------------------------------------------------------
// Author : Common //主类
//Function : IntBuffer_demo
public class IntBuffer_demo { public static void main(String[] args) {
// TODO 自动生成的方法存根 IntBuffer buf = IntBuffer.allocate(10); //开辟10个大小的缓冲区
IntBuffer read = null; //定义缓冲区对象
for(int i=0;i<10;i++){
buf.put(2*i+1);
}
read = buf.asReadOnlyBuffer(); //创建只读缓冲区
buf.flip(); //重设缓冲区
System.out.println("主缓冲区中的内容:");
while(buf.hasRemaining()){
int x = buf.get(); //取出当前内容
System.out.print(x+"、");
}
System.out.println();
read.put(30); //错误,不可写
} }

Java——新IO 缓冲区与Buffer

Java——新IO 缓冲区与Buffer