一直搞不懂,今天看了看源码,原来是这样的。
它们都是抽象类Buffer中的函数,有四个变量:
- mark书签
- positiion当前位置
- limit受限位置
- capacity总容量
满足关系:mark<=position<=limit<=capacity
三个函数clear、flip、rewind其实是这样的:
public final Buffer clear() {
limit = capacity;
position = 0;
mark = -1;
return this;
}
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
flip一般是读完数据后调用,prepare for writing
clear一般是写完数据后调用,prepare for reading
作为一个例子,看看thinking in java中的例子:
package java2.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* Created by fhqplzj on 16-10-26 at 下午4:36.
*/
public class ChannelCopy {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("arguments: sourcefile destfile");
System.exit(1);
}
FileChannel in = new FileInputStream(args[0]).getChannel(),
out = new FileOutputStream(args[1]).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while (in.read(buffer) != -1) {
// Prepare for writing
buffer.flip();
out.write(buffer);
// Prepare for reading
buffer.clear();
}
}
}
当然,其实并没有必要那么做,只是为了使用flip和clear:
拷贝文件更简单的方式:
// 方式一:
in.transferTo(0, in.size(), out);
// 方式二:
out.transferFrom(in, 0, in.size());