1、bytebuffer有四个属性
1、position :
当前读取的位置;调用position()时获取;调用get()方法时指向读取位置的下一位;调用put()时指向当前写入的位置的下一位;
2、mark :
调用mark()时标记当前读取的位置值;设置为负值时废弃次标记;
3、limit:
读取的界限;limit<=capacity;
4、capacity :
容量;bytebuffer.allocate(capacity);
2、写入完准备读取之前,必须调用flip()方法;
flip方法源码:
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
3、重复使用时,必须在下一次调用之前调用clear();
clear方法源码:
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
4、reset与rewind
reset将position设置为mark的值
public final Buffer reset() {
int m = mark;
if (m < 0)
throw new InvalidMarkException();
position = m;
return this;
}
rewind将position设置为0
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
4、复制文件示例
// 源文件
ch3 = new FileInputStream(filePath).getChannel();
// 目标文件
ch4 = new FileOutputStream("E:/1s.txt").getChannel();
// int size = new Long(ch3.size()).intValue();
int bufferSize = 10;
ByteBuffer bb = ByteBuffer.allocate(bufferSize);
StringBuilder content = new StringBuilder();
while (ch3.read(bb) != -1) {
bb.flip();
ch4.write(bb);
bb.clear();
}
5、直接bytebuffer转字符串输出
Charset.forName(System.getProperty("file.encoding"))
.decode(bytebuffer);
6、bytebuffer的视图
ByteBuffer bb = ByteBuffer
.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, 'a' });
try {
// set position 0
bb.rewind();
// print as byte(1)
while (bb.hasRemaining()) {
System.out.print(bb.position() + "=" + bb.get() + " ");
}
System.out.println();
// print as char(2)
CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
while (cb.hasRemaining()) {
System.out.print(cb.position() + "=" + cb.get() + " ");
}
System.out.println();
// print as float(4)
FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();
while (fb.hasRemaining()) {
System.out.print(fb.position() + "=" + fb.get() + " ");
}
System.out.println();
// print as int (4)
IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
while (ib.hasRemaining()) {
System.out.print(ib.position() + "=" + ib.get() + " ");
}
System.out.println();
// print as long
LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();
while (lb.hasRemaining()) {
System.out.print(lb.position() + "=" + lb.get() + " ");
}
System.out.println();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}