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;
            }
        }
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值