NIO

Java NIO 簡介

Java NIO(New IO)是從 Java 1.4 版本開始引入的一個新的 IO API,可以替代標準的 Java IO API。NIO 與原來的 IO 有同樣的作用和目的,但是使用的方式完全不同,NIO支持面向緩沖區的、基于通道的 IO 操作。NIO 將以更加高效的方式進行文件的讀寫操作。

Java NIO 與 IO 的主要區別

image.png

通道(Channel)與緩沖區(Buffer)

Java NIO 系統的核心在于:通道(Channel)和緩沖區(Buffer)。通道表示打開到 IO 設備(例如:文件、套接字)的連接。若需要使用 NIO 系統,需要獲取用于連接 IO 設備的通道以及用于容納數據的緩沖區。然后操作緩沖區,對數據進行處理。

舉個例子,通道就像鐵路,而緩沖區就像火車,鐵路本身不能運輸數據,火車才可以運輸。

緩沖區(Buffer)

一個用于特定基本數據類型的容器。由 java.nio 包定義的,所有緩沖區都是 Buffer 抽象類的子類。

Java NIO 中的 Buffer 主要用于與 NIO 通道進行交互,數據是從通道讀入緩沖區,從緩沖區寫入通道中的。

Buffer 就像一個數組,可以保存多個相同類型的數據。根據數據類型不同(boolean 除外),有以下 Buffer 常用子類:

  • ByteBuffer
  • CharBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer

上述 Buffer 類 他們都采用相似的方法進行管理數據,只是各自管理的數據類型不同而已。都是通過如下方法獲取一個 Buffer 對象:

static XxxBuffer allocate(int capacity) : 創建一個容量為 capacity 的 XxxBuffer 對象

緩沖區的基本屬性

  • 容量 (capacity) :表示 Buffer 最大數據容量,緩沖區容量不能為負,并且創建后不能更改。

  • 限制 (limit):第一個不應該讀取或寫入的數據的索引,即位于 limit 后的數據不可讀寫。緩沖區的限制不能為負,并且不能大于其容量。(可以操作數據的大小)

  • 位置 (position):下一個要讀取或寫入的數據的索引。緩沖區的位置不能為負,并且不能大于其限制。

    通過下面的代碼可以更好的理解 capacity、limit、以及 position:

    String str = "abcde";
    
    // 1. 分配一個指定大小的緩沖區
    ByteBuffer buf = ByteBuffer.allocate(1024);
    
    System.out.println("-----------------allocate()----------------");
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    
    // 2. 利用 put() 存入數據到緩沖區中
    buf.put(str.getBytes());
    
    System.out.println("-----------------put()----------------");
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    
    // 3. 切換讀取數據模式
    buf.flip();
    
    System.out.println("-----------------flip()----------------");
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    
    // 4. 利用 get() 讀取緩沖區中的數據
    byte[] dst = new byte[buf.limit()];
    buf.get(dst);
    System.out.println(new String(dst, 0, dst.length));
    
    System.out.println("-----------------get()----------------");
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    
    // 5. rewind() : 可重復讀
    buf.rewind();
    
    System.out.println("-----------------rewind()----------------");
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    
    // 6. clear() : 清空緩沖區. 但是緩沖區中的數據依然存在,但是處于“被遺忘”狀態,數據還在,但是指針位置變了
    buf.clear();
    
    System.out.println("-----------------clear()----------------");
    System.out.println(buf.position());
    System.out.println(buf.limit());
    System.out.println(buf.capacity());
    
    // 所以這里還是能取得到數據的
    System.out.println((char) buf.get());
    
    image.png

    運行結果:

    -----------------allocate()----------------
    0
    1024
    1024
    -----------------put()----------------
    5
    1024
    1024
    -----------------flip()----------------
    0
    5
    1024
    abcde
    -----------------get()----------------
    5
    5
    1024
    -----------------rewind()----------------
    0
    5
    1024
    -----------------clear()----------------
    0
    1024
    1024
    a
    
  • 標記 (mark)與重置 (reset):標記是一個索引,通過 Buffer 中的 mark() 方法指定 Buffer 中一個特定的 position,之后可以通過調用 reset() 方法恢復到這個 position(標記,表示記錄當前 position 的位置。可以通過 reset() 恢復到 mark 的位置)。

    String str = "abcde";
    
    ByteBuffer buf = ByteBuffer.allocate(1024);
    
    buf.put(str.getBytes());
    
    buf.flip();
    
    byte[] dst = new byte[buf.limit()];
    buf.get(dst, 0, 2);
    System.out.println(new String(dst, 0, 2));
    System.out.println(buf.position());
    System.out.println("--------------");
    
    // mark() : 標記
    buf.mark();
    
    buf.get(dst, 2, 2);
    System.out.println(new String(dst, 2, 2));
    System.out.println(buf.position());
    
    System.out.println("--------------");
    
    // reset() : 恢復到 mark 的位置
    buf.reset();
    System.out.println(buf.position());
    
    // 判斷緩沖區中是否還有剩余數據
    if(buf.hasRemaining()){
    
        // 獲取緩沖區中可以操作的數量
        System.out.println(buf.remaining());
    }
    

    標記、位置、限制、容量遵守以下不變式: 0 <= mark <= position <= limit <= capacity

緩沖區的數據操作

Buffer 所有子類提供了兩個用于數據操作的方法:get() 與 put() 方法。

  • 獲取 Buffer 中的數據
    • get() :讀取單個字節
    • get(byte[] dst):批量讀取多個字節到 dst 中
    • get(int index):讀取指定索引位置的字節(不會移動 position)
  • 放入數據到 Buffer 中
    • put(byte b):將給定單個字節寫入緩沖區的當前位置
    • put(byte[] src):將 src 中的字節寫入緩沖區的當前位置
    • put(int index, byte b):將指定字節寫入緩沖區的索引位置(不會移動 position)

Buffer 的常用方法

image.png

通道(Channel)

由 java.nio.channels 包定義的。Channel 表示 IO 源與目標打開的連接。Channel 類似于傳統的“流”。只不過 Channel 本身不能直接訪問數據,Channel 只能與 Buffer 進行交互。

Java 為 Channel 接口提供的最主要實現類如下:

  • FileChannel:用于讀取、寫入、映射和操作文件的通道。
  • DatagramChannel:通過 UDP 讀寫網絡中的數據通道。
  • SocketChannel:通過 TCP 讀寫網絡中的數據。
  • ServerSocketChannel:可以監聽新進來的 TCP 連接,對每一個新進來的連接都會創建一個 SocketChannel。

獲取通道

獲取通道的一種方式是對支持通道的對象調用 getChannel() 方法。支持通道的類如下:

  • FileInputStream
  • FileOutputStream
  • RandomAccessFile
  • DatagramSocket
  • Socket
  • ServerSocket

獲取通道的其他方式是使用 Files 類的靜態方法 newByteChannel() 獲取字節通道。或者通過通道的靜態方法 open() 打開并返回指定通道。

通道的數據傳輸

非直接緩沖區

// 文件的復制
FileInputStream fileInputStream = new FileInputStream("1.jpg");
FileChannel inputStreamChannel = fileInputStream.getChannel();

FileOutputStream fileOutputStream = new FileOutputStream("2.jpg");
FileChannel outputStreamChannel = fileOutputStream.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024);
// 將通道數據存入緩沖區
while (inputStreamChannel.read(buffer)!=-1){
        buffer.flip();
        outputStreamChannel.write(buffer);
        buffer.clear();
}

直接緩沖區

// 直接緩沖區
FileChannel inChannel = FileChannel.open(Paths.get("d:/1.mkv"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("d:/2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
        
// 內存映射文件
MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
        
// 直接對緩沖區進行數據的讀寫操作
byte[] dst = new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMappedBuf.put(dst);

通道之間的數據傳輸

FileChannel inChannel = FileChannel.open(Paths.get("d:/1.mkv"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("d:/2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
        
inChannel.transferTo(0, inChannel.size(), outChannel);
// outChannel.transferFrom(inChannel, 0, inChannel.size());

分散(Scatter)和聚集(Gather)

分散讀取(Scattering Reads)是指從 Channel 中讀取的數據“分散”到多個 Buffer 中。

image.png

按照緩沖區的順序,從 Channel 中讀取的數據依次將 Buffer 填滿。

聚集寫入(Gathering Writes)是指將多個 Buffer 中的數據“聚集”到 Channel。

image.png

注意:按照緩沖區的順序,寫入 position 和 limit 之間的數據到 Channel 。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容