nio 创建缓冲区的方法选择

allocate 还是 allocateDirect

http://stevex.blog.51cto.com/4300375/1582209

NIO读写文件优劣

http://blog.csdn.net/gzu_imis/article/details/21109753


NIO读取

public static void main(String[] args)
    {
        ByteBuffer bb = ByteBuffer.allocate(10);
        bb.put(ByteBuffer.wrap("abc".getBytes()));
        byte[] bytes = new byte[1024];
        int postion = bb.position();
        bb.flip();
        //读取bb的postion 到 limit 之间的数据
        bb.get(bytes, 0, postion);
        // 输出abc
        System.out.println(new String(bytes));
    }



ByteBuffer.get() 源码 HeapByteBuffer

public ByteBuffer get(byte[] dst, int offset, int length) {
 checkBounds(offset, length, dst.length);
 if (length > remaining())
    throw new BufferUnderflowException();
 System.arraycopy(hb, ix(position()), dst, offset, length);
 position(position() + length);
 return this;
    }



可以看到是从缓冲区的position 位置开始读取数据的,所以需要先做一步bb.flip 才可以读取数据
08-28 14:01