具體思路:打開一個文件,把文件以字節讀到buffer中,再把buffer進行一次flip,就可以把buffer寫入到一個文件中了。如果沒有clear方法會產生死循環,一直把buffer讀到文件中。
不寫clear方法分析:第一次read之後position等於limit,read等於buffer字節數,flip之後,position爲0,limit不變,把buffer讀進文件中,position等於limit。再次循環,因爲position等於limit,所以讀取數量爲0,所以read等於0,循環不跳出,flip之後,position爲0,再次把buffer讀進文件。read一直爲0,循環不退出
package com.wave.NioTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioTest {
public static void main(String[] args) throws Exception{
FileInputStream fileInputStream = new FileInputStream("input.txt");
FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
FileChannel inputChannel = fileInputStream.getChannel();
FileChannel outputChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while(true){
byteBuffer.clear();
int read = inputChannel.read(byteBuffer);
if(read == -1){
break;
}
byteBuffer.flip();
outputChannel.write(byteBuffer);
}
inputChannel.close();
outputChannel.close();
}
}