---
title: "java.nio.Buffer flip()方法jdk中文翻译错误"
author: "walsh"
date: "2009-08-15T14:24:10Z"
tags: []
slug: "java-nio-buffer-flip-jdk"
draft: false
lastmod: "2009-08-15T14:24:10Z"
id: 450114
url: "https://walsh.iteye.com/blog/450114"
---

今天在看《Java编程思想》的时候，碰到java.nio.Buffer flip()方法，不明白是干什么用的，于是就赶快查看中文API，API上面翻译的是："<span style="color:red">反转此缓冲区。首先对当前位置设置限制，然后将该位置设置为零。如果已定义了标记，则丢弃该标记</span>。";
    说实话，看了几遍，真还不明白说的是什么意思，于是就查看英文API，是这样说的：<span style="color:red">Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded.</span>，意思大概是这样的：<span style="color:red">调换这个buffer的当前位置，并且设置当前位置是0</span>。说的意思就是：<span style="color:red">将缓存字节数组的指针设置为数组的开始序列即数组下标0</span>。这样就可以从buffer开头，对该buffer进行遍历（读取）了。
  
    实例代码（借用Java编程思想P552的代码）：
    
```java
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缓冲区的第一个位置。