视图缓冲器,可以让我们通过某个特定的基本数据类型的视窗查看其底层的ByteBuffer。ByteBuffer依然是实际存储数据的地方,“支持”着前面的视图,因此对视图的任何修改都会映射成为对ByteBuffer中数据的修改

public class IntBufferDemo {
    private static final int BSIZE=1024;
    public static void main(String[] args){
        ByteBuffer buffer=ByteBuffer.allocate(BSIZE);
        IntBuffer ib=buffer.asIntBuffer();
        ib.put(new int[]{11,42,33,24});
        System.out.println(ib.get(2));
        ib.put(2,111);
        ib.flip();
        while (ib.hasRemaining()){
            int m=ib.get();
            System.out.println(m);
        }
    }
}

一旦底层的ByteBuffer通过视图缓冲器填满了整数或其他基本类型时,就可以直接被写到通道中了。

public class ViewBuffers {
    public static void main(String[] args){
        ByteBuffer buffer=ByteBuffer.wrap(new byte[]{0,0,0,0,0,0});
        buffer.rewind();
        while (buffer.hasRemaining())
            System.out.println(buffer.position()+"-->"+buffer.get());
        buffer.rewind();
        CharBuffer cb=buffer.asCharBuffer();
        while (cb.hasRemaining())
            System.out.print(cb.get());
        buffer.rewind();
        FloatBuffer fb=buffer.asFloatBuffer();
        while (fb.hasRemaining())
            System.out.println(fb.get());
        IntBuffer ib=buffer.asIntBuffer();
        while (ib.hasRemaining())
            System.out.print(ib.get());
    }
}

ByteBuffer通过一个被“包装”过的8字节数组产生,然后通过各种不同的基本类型的视图缓冲器显示了出来。我们可以在下图中看到,当从不同类型的缓冲器读取时,数据显示的方式也不同。

视图缓冲器

相关文章:

  • 2021-10-14
  • 2021-08-26
  • 2021-10-31
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2021-05-24
猜你喜欢
  • 2021-10-08
  • 2021-09-08
  • 2021-12-24
相关资源
相似解决方案