java.nio.Buffer 中的 flip()方法

1.flip()方法用来将缓冲区准备为数据传出状态,这经过将limit设置为position的当前值,再将 position的值设为0来实现:

后续的get()/write()调用将从缓冲区的第一个元素开始检索数据,直到到达limit指示的位置。下面是使用flip()方法的例子:java

// ... put data in buffer with put() or read() ...


buffer.flip(); // Set position to 0, limit to old position
while (buffer.hasRemaining()) 
// Write buffer data from the first element up to limit
channel.write(buffer);

2. flip()源码:编程

public final Buffer flip() {  
    limit = position;  
    position = 0;  
    mark = -1;  
    return this;  
}  


3.数组

实例代码(借用Java编程思想P552的代码): 
[java] view plain copy print?
package cn.com.newcom.ch18;  
  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.RandomAccessFile;  
import java.nio.ByteBuffer;  
import java.nio.channels.FileChannel;  
  
/** 
 * 获取通道 
 *  
 * @author zhq 
 *  
 */  
public class GetChannel {  
    private static final int SIZE = 1024;  
  
    public static void main(String[] args) throws Exception {  
        // 获取通道,该通道容许写操做  
        FileChannel fc = new FileOutputStream("data.txt").getChannel();  
        // 将字节数组包装到缓冲区中  
        fc.write(ByteBuffer.wrap("Some text".getBytes()));  
        // 关闭通道  
        fc.close();  
  
        // 随机读写文件流建立的管道  
        fc = new RandomAccessFile("data.txt", "rw").getChannel();  
        // fc.position()计算从文件的开始到当前位置之间的字节数  
        System.out.println("此通道的文件位置:" + fc.position());  
        // 设置此通道的文件位置,fc.size()此通道的文件的当前大小,该条语句执行后,通道位置处于文件的末尾  
        fc.position(fc.size());  
        // 在文件末尾写入字节  
        fc.write(ByteBuffer.wrap("Some more".getBytes()));  
        fc.close();  
  
        // 用通道读取文件  
        fc = new FileInputStream("data.txt").getChannel();  
        ByteBuffer buffer = ByteBuffer.allocate(SIZE);  
        // 将文件内容读到指定的缓冲区中  
        fc.read(buffer);  
        buffer.flip();// 此行语句必定要有  
        while (buffer.hasRemaining()) {  
            System.out.print((char) buffer.get());  
        }  
        fc.close();  
    }  
}  
  

注意:buffer.flip();必定得有,若是没有,就是从文件最后开始读取的,固然读出来的都是byte=0时候的字符。经过buffer.flip();这个语句,就能把buffer的当前位置更改成buffer缓冲区的第一个位置。dom

相关文章
相关标签/搜索