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

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

大家好,又见面了,我是全栈君。

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

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

// ... 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缓冲区的第一个位置。

转载于:https://my.oschina.net/u/2263272/blog/1556275

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/108085.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号