首页  

java NIO buffer     所属分类 nio 浏览量 792
NIO buffer 与NIO Channel交互时使用
数据从Channel中读取出来放入buffer,或者从buffer中读取出来写入Channel

使用buffer读写数据基本操作
将数据写入buffer
调用buffer.flip()
将数据从buffer中读取出来
调用buffer.clear()或者buffer.compact()

buffer 写入时,会跟踪写入了多少数据 
读取时调用flip() 将buffer从写模式切换成读模式,读模式中只能读取写入的数据,而非整个buffer

数据读完后,清空buffer供下次使用,
调用clear() 或者 compact()
clear方法清空整个buffer
compact方法只清除已经读取的数据,未读取的数据会被移到buffer的开头,写入数据从当前数据的末尾开始

Capacity Position Limit

Capacity 
缓冲区容量 ,缓冲区创建时设定,不能修改

Limit    
写模式中等于buffer的大小,即capacity 
读模式中为可读的最大位置
调用filp()方法切换成读模式时,limit的值变成position的值,position指向0

Position
下一个读或写的位置
get 和 put 会改变 position

创建buffer

ByteBuffer buf = ByteBuffer.allocate(64);
CharBuffer buf = CharBuffer.allocate(128);

buffer 写入
Channel中写入buffer
buffer  put()方法 

int bytesRead = inChannel.read(buf);
buf.put(127)


flip
写模式切换成读模式,limit设置为position,position设置成0
  

从buffer中读取数据
从buffer中读取数据到channel中
使用buffer的get()方法

int bytesWritten = inChannel.write(buf);
byte b = buf.get();


rewind
将position设置为0,可以从头开始重新读取数据,limit不变


clear 和 compact 
读完数据想要重新写入数据时,可以调用clear或者compact方法
clear ,  position设置为0,limit设置为capacity
如果还有没有读完的数据,但想先写数据,可以用compact()方法
未读数据会放在buffer前端,可以在未读数据之后写新的数据

mark reset 

buffer.mark();
// 调用buffer.get()方法若干次
// set position back to mark
buffer.reset(); 

equals  和 compareTo

equals
是是否同一种数据类型的buffer
未读取的数据是否相等

compareTo
跟 equals ,比较未读取的


以 ByteBuffer 为例

public boolean equals(Object ob) {
    if (this == ob)
        return true;
    if (!(ob instanceof ByteBuffer))
        return false;
    ByteBuffer that = (ByteBuffer)ob;
    if (this.remaining() != that.remaining())
        return false;
    int p = this.position();
    for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
        if (!equals(this.get(i), that.get(j)))
            return false;
    return true;
}


public int compareTo(ByteBuffer that) {
    int n = this.position() + Math.min(this.remaining(), that.remaining());
    for (int i = this.position(), j = that.position(); i < n; i++, j++) {
        int cmp = compare(this.get(i), that.get(j));
        if (cmp != 0)
            return cmp;
    }
    return this.remaining() - that.remaining();
}

private static int compare(byte x, byte y) {
    return Byte.compare(x, y);
}

上一篇     下一篇
第一个 NIO server 例子

Java NIO 注意点

Java NIO写事件处理技巧

Java NIO pipe

java NIO FileChannel

Java NIO Scatter Gather