美文网首页
2、java.nio、ByteBuffer的简单使用

2、java.nio、ByteBuffer的简单使用

作者: 四月的谎言v5 | 来源:发表于2019-03-13 21:50 被阅读0次
    //基本概念
    limit 对缓存区的读写操作以limit值为上限
    position 当前游标位置(也就是当前操作的位置)
    capacity 缓存区容量(一般和limit一样)
    

    常用方法

    
    //分配缓存区大小
    public static ByteBuffer allocate(int capacity) {
            if (capacity < 0)
                throw createCapacityException(capacity);
            return new HeapByteBuffer(capacity, capacity);
        }
    
    //写入内容
    public ByteBuffer put(byte[] src, int offset, int length) {
            checkBounds(offset, length, src.length);
            if (length > remaining())
                throw new BufferOverflowException();
            int end = offset + length;
            for (int i = offset; i < end; i++)
                this.put(src[i]);
            return this;
        }
    
    //读取内容
      public ByteBuffer get(byte[] dst, int offset, int length) {
            checkBounds(offset, length, dst.length);
            if (length > remaining())
                throw new BufferUnderflowException();
            int end = offset + length;
            for (int i = offset; i < end; i++)
                dst[i] = get();
            return this;
        }
    
    //作用转换为读模式,操作上限修改为当前操作的位置,然后游标置0,
    //这样就可以从开头读取
    public Buffer flip() {
            limit = position;
            position = 0;
            mark = -1;
            return this;
        }
    
    //重置当前读写位置,清除所有内容
    public Buffer clear() {
            position = 0;
            limit = capacity;
            mark = -1;
            return this;
    
    //重置当前游标不清除内容,一般配合flip多次读取操作
    public Buffer rewind() {
            position = 0;
            mark = -1;
            return this;
    
    //在当前游标位置设置标记
    public Buffer mark() {
            mark = position;
            return this;
        }
    
    //将游标的位置设置到上一次mark标记的位置
    public Buffer reset() {
            int m = mark;
            if (m < 0)
                throw new InvalidMarkException();
            position = m;
            return this;
        }
    
    public static void main(String[] args) {
        ByteBuffer buff = ByteBuffer.allocate(1024);
        // 写入数据
        buff.put("hello".getBytes());
        System.out.println(
            "当前游标: " + buff.position() + " 当前读写上限: " + buff.limit() + " 当前容量:" + buff.capacity());
        // 设置当前读写上限为当前游标也就是limit=position 这样就不会读的时候分配的1024字节全部读
        buff.flip();
        System.out.println(
            "当前游标: " + buff.position() + " 当前读写上限: " + buff.limit() + " 当前容量:" + buff.capacity());
        // 创建当前缓冲区上限的字节数组
        byte[] ibuff = new byte[buff.limit()];
        // 读入到数组
        buff.get(ibuff);
        // 转换成字符串
        String s = new String(ibuff);
        System.out.println(s);
        // 重置缓存区
        buff.clear();
      }
    

    相关文章

      网友评论

          本文标题:2、java.nio、ByteBuffer的简单使用

          本文链接:https://www.haomeiwen.com/subject/esexmqtx.html