NIO系列1:Channel的理解

weixin_34148340發表於2017-03-21

本文參考至:http://ifeve.com/channels/

其實可以將Channel理解為流,不同的地方在於:
1、通道既可以從中讀取資料,又可以寫資料到通道。但流的讀寫通常是單向的。
2、通道可以非同步地讀寫。
3、通道中的資料總是要先讀到一個Buffer,或者總是要從一個Buffer中寫入。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO中FileChannle的建立
 * Channel的理解
 * @author JM
 * @2017-3-21
 */
public class FileChannleMake {
    public static void main(String[] args) throws IOException {
        // 獲取檔案物件
        File file = new File("F:/jia.txt");
        // 將檔案物件轉為流的形式
        FileInputStream fileInput = new FileInputStream(file);
        // 將輸入流轉為channel物件
        FileChannel fileChannel = fileInput.getChannel();
        // 用於儲存從channel讀取到的資料,最大容量:48bytes
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        // 從檔案中讀寫資料,下面這行程式碼表示從該通道讀取一個位元組序列到給定的緩衝區。通道是可以非同步讀寫的!!!
        // 每次從通道讀48個位元組到byteBuffer中,讀過的資料不能再讀
        int bytesRead = fileChannel.read(byteBuffer);
        while (bytesRead != -1) {
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                System.out.print((char) byteBuffer.get());
            }
            System.out.println(" ----read " + bytesRead);
            byteBuffer.clear();
            // 當byteBuffer全部讀出後,又會繼續從channel讀資料到byteBuffer中,直到讀完channel中的資料
            bytesRead = fileChannel.read(byteBuffer);
        }

        //通過下面的程式碼,可以清晰的發現。FileChannel中的資料只要讀出之後就會被刪掉
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(48);
        int bytesRead1 = fileChannel.read(byteBuffer);
        System.out.println("ssssssssss" + bytesRead1);
        while (bytesRead1 != -1) {
            System.out.println("ssssssssssasasas----end" + bytesRead1);
            byteBuffer1.flip();
            while (byteBuffer.hasRemaining()) {
                System.out.print((char) byteBuffer1.get());
            }
            System.out.println(" ----read " + bytesRead1);
            byteBuffer.clear();
            bytesRead1 = fileChannel.read(byteBuffer);
        }
    }
}

讀者可以嘗試看看然後執行上面的程式碼。

這裡簡單介紹一下FileChannel
Java NIO中的FileChannel是一個連線到檔案的通道。可以通過檔案通道讀寫檔案。在使用FileChannel之前,必須先開啟它。但是,我們無法直接開啟一個FileChannel,需要通過使用一個InputStream、OutputStream或RandomAccessFile來獲取一個FileChannel例項。(上面例子我是通過FileInputStream 來獲取FileChannel的)

相關文章