一、一般來說緩衝區和通道結合在一起使用,寫入文件的時候,需要先存放在緩衝區,然後通過通道寫入。讀取文件的時候也類似,通過通道讀取在緩衝區。然後通過緩衝區獲取文件內容。
Buffer針對每一種java基本類型都有實現。Channel針對不同的使用對象也有不同的實現,一般常見的爲FileChannel與SocketChannel兩類。
Buffer底層實現爲數組,有三個重要的參數,position,limit,capacity,分別代表當前位置,剩餘空間,最大容量
Buffer有兩種模式,讀模式與寫模式。通過方法flip()進入讀取模式,clear()方法進入寫入模式。
二、代碼實例:
package nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* NIO拷貝文件(Buffer與FileChannel的使用實例)
*
* @author
* @version $Id: CopyFile.java, v 0.1 2014年3月2日 下午12:34:55 Exp $
*/
public class CopyFile {
public static void main(String[] args) throws Exception {
String srcFile = "D://1.wmv";
String targetFile = "D://2.wmv";
FileInputStream fin = null;
FileOutputStream fout = null;
FileChannel finc = null;
FileChannel foutc = null;
try {
fin = new FileInputStream(srcFile);
fout = new FileOutputStream(targetFile);
finc = fin.getChannel();
foutc = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int n = finc.read(buffer);
if (n == -1) {
break;
}
buffer.flip();
foutc.write(buffer);
}
} catch (Exception e) {
e.fillInStackTrace();
} finally {
if (finc != null) {
finc.close();
}
if (foutc != null) {
foutc.close();
}
if (fin != null) {
fin.close();
}
if (fout != null) {
fout.close();
}
}
}
}
上面的代碼中,通過通道將文件內容讀取到緩衝區,然後通過通道寫入到文件。Buffer在文件讀取之前調用clear,在文件寫入之前調用flip。