javaNIO中关于ByteBuffer的用法
作者:15191806282
这篇文章主要介绍了javaNIO中关于ByteBuffer的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
javaNIO中ByteBuffer用法
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;
}
}
}使用isoparser包,报错java.nio.bytebuffer.limiy(i)
问题描述
使用isoparser包,报错java.nio.bytebuffer.limiy(i)
IsoFile isoFile = new IsoFile("文件路径");原因分析
我使用的是isoparser的1.9.41,某些依赖包版本太低不支持
解决方案
换成更低的版本1.9.39
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
