1. 程式人生 > >NIO快讀寫

NIO快讀寫

NIO是塊I/O,區別於原來的的流I/O,從java1.4開始加入,有更高的效率。
NIO的輸入輸出加入通道的概念,用通道連線檔案進行I/O,通道另一頭連線到一個緩衝區(如java.nio.Buffer)。
如我們可以從FileInputStream獲取一個通道fcin,然後從通道讀取資料到緩衝區buff:fcin.read(buff),這樣資料就從檔案進入緩衝區。
以下例子:
讀取一個檔案,寫入另一個檔案

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class CopyFile {
static public void main(String args[]) throws Exception { String file_in = "e:/mnt/in"; String file_out = "e:/mnt/out"; FileInputStream fin = new FileInputStream(file_in); FileOutputStream fout = new FileOutputStream(file_out); FileChannel fcin = fin.getChannel
(); FileChannel fcout = fout.getChannel(); ByteBuffer byteBuf = ByteBuffer.allocate(1024); while (true) { byteBuf.clear(); if (fcin.read(byteBuf) == -1) break; byteBuf.flip(); fcout.write(byteBuf); } }
}

緩衝區的操作:
除了從通道讀資料到緩衝區,或者將緩衝區資料寫入通道。還可以對緩衝區進行直接讀寫,用put和get函式。