nio學習之channel,基於流的方式獲取channel
阿新 • • 發佈:2018-12-13
package nio; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; //測試channel //使用基於流的channel方式 public class testChannel { public static void main(String[] a){ //傳統方式的channel方式 try { FileInputStream fileInputStream = new FileInputStream("e:/11.txt");//獲取輸入流 FileChannel fileChannel = fileInputStream.getChannel();//獲取channel FileOutputStream fileOutputStream = new FileOutputStream("e:/22.txt");//獲取輸出流 FileChannel fileChannel1 = fileOutputStream.getChannel(); //建立緩衝區 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); //從通道中讀取資料 while (fileChannel.read(byteBuffer) != -1) { //轉換為讀資料模式 byteBuffer.flip(); fileChannel1.write(byteBuffer); //清空緩衝區 byteBuffer.clear(); } } catch (Exception e) { e.printStackTrace(); } } }
記得要關閉流!本例沒有關閉。
基於記憶體對映檔案方式的檔案讀寫
package nio; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.OpenOption; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; //使用記憶體對映檔案的方式 //加速輸入輸出流的傳遞 //使用1.7以後的新的建立管道的方式 public class testMapChannel { public static void main(String[] a){ try { //獲取檔案的channel,並且以讀的模式 FileChannel fileChannel = FileChannel.open(Paths.get("e:/11.txt"), StandardOpenOption.READ); //獲取檔案的channel,以寫的模式 FileChannel fileChannel1 = FileChannel.open(Paths.get("e://33.txt"),StandardOpenOption.WRITE,StandardOpenOption.CREATE); //使用記憶體對映檔案的方式,基於channel的傳輸完成檔案的讀寫操作 fileChannel.transferTo(0,fileChannel.size(),fileChannel1); } catch (IOException e) { e.printStackTrace(); } } } 基於記憶體對映檔案的方式,檔案的讀寫完全由os來操作,因此會存在不穩定性,應在特定的場合選擇使用