ByteBuffer类是在javaNIO中常常使用的一个缓冲区类,使用ByteBuffer可以进行高效的IO操作
下来我们看一下ByteBuffer类的常用方法:
ByteBuffer.allocate();或者ByteBuffer.wrap();创建ByteBuffer
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
public static ByteBuffer wrap(byte[] array,
int offset, int length)
{
try {
return new HeapByteBuffer(array, offset, length);
} catch (IllegalArgumentException x) {
throw new IndexOutOfBoundsException();
}
}
读写的方法就read()、write(),在这之中我们看一下ByteBuffer内部字段
position:当前读取的位置
mark:为某一读过的位置做标记,便于有时候回退到该位置
capacity:初始化时候的容量
limit:读写的上限,limit <= capacity
flip()方法写完数据需要开始读的时候,将position复位到0,并将limit设为当前position
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
clear()方法是将position置为0,并不清除buffer内容
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
*mark()方法是标记,reset()方法是回到标记
public final Buffer mark() {
mark = position;
return this;
}
public final Buffer reset() {
int m = mark;
if (m < 0)
throw new InvalidMarkException();
position = m;
return this;
}
下来看一个例子
public void test() throws IOException
{
ByteBuffer buff = ByteBuffer.allocate(256);
FileChannel in = null;
FileChannel out = null;
try
{
in = new FileInputStream("filein").getChannel();
out = new FileOutputStream("fileout").getChannel();
while(fin.read(buff) != -1) {
buff.flip();
fout.write(buff);
buff.clear();
}
}
catch (FileNotFoundException e)
{
throw e;
} finally {
try {
if(in != null) {
in.close();
}
if(fout != null) {
out.close();
}
} catch(IOException e) {
throw e;
}
}
}