public static void main(String[] args) {
ByteBuffer buffer = java.nio.ByteBuffer.allocate(10);
System.out.println("buffer type class: "+ buffer.getClass());//java.nio.HeapByteBuffer
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
System.out.println("readOnlyBuffer type class: "+ readOnlyBuffer.getClass());//java.nio.HeapByteBufferR
}
protected HeapByteBufferR(byte[] buf, int mark, int pos, int lim, int cap, int off)
{
super(buf, mark, pos, lim, cap, off);
this.isReadOnly = true;
}
一、入门demo
从上面的代码我们可以看出默认的申请一个10byte长度的数组默认是HeapByteBuffer。
当我们把buffer转化为readonly模式的时候它其实内部又new了一个HeapByteBufferR。设置成员变量isReadOnly为true
public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer>
{
final byte[] hb; //元素数组
final int offset; //下标偏移量,从offset+index确定数组中的位置
boolean isReadOnly; //是否只读
}
二、API操作
package demo1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import io.netty.buffer.ByteBuf;
public class demo2 {
public static void main(String[] args) throws Exception {
FileInputStream inputStream = new FileInputStream("input.txt");
FileOutputStream outputStream = new FileOutputStream("output.txt");
FileChannel inputChannel =inputStream.getChannel();
FileChannel outputChannel = outputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(512);
while(true) {
//clear 后position=0 limit=capacity mark=-1
buffer.clear();
//底层调用了IOUtil类write()调用了buffer.put()方法
int read = inputChannel.read(buffer);//position++,这里注意若数据没有读完但是buffer满了,那么返回0.如数据已经读完返回-1
System.out.println("read:"+read);
if(-1 == read) {
break;
}
buffer.flip();//limit= position;position=0;
//底层调用了buffer.get()方法
outputChannel.write(buffer);//position++
}
inputChannel.close();
outputChannel.close();
}
}