Java NIO系列教程(二) Channel

Java NIO系列教程(二) Channel

Java NIO 的通道相似流,但又有些不一樣:java

  • 既能夠從通道中讀取數據,又能夠寫數據到通道。但流的讀寫一般是單向的。
  • 通道能夠異步地讀寫。
  • 通道中的數據老是要先讀到一個 Buffer,或者老是要從一個 Buffer 中寫入。

正如上面所說,從通道讀取數據到緩衝區,從緩衝區寫入數據到通道。以下圖所示:編程

Channel和Buffer

Channel的實現

這些是 Java NIO 中最重要的通道的實現:服務器

java.nio.channels.Channel 接口:
    |--FileChannel
    |--SocketChannel
    |--ServerSocketChannel
    |--DatagramChannel
  • FileChannel 從文件中讀寫數據。
  • DatagramChannel 能經過 UDP 讀寫網絡中的數據。
  • SocketChannel 能經過 TCP 讀寫網絡中的數據。
  • ServerSocketChannel 能夠監聽新進來的 TCP 鏈接,像 Web 服務器那樣。對每個新進來的鏈接都會建立一個 SocketChannel。

通道的獲取

  1. Java 針對支持通道的類提供了 getChannel() 方法。網絡

    • 本地IO FileInputStream/FileOutputStream/RandomAccessFile併發

    • 網絡IO Socket/ServerSocket/DatagramSocketdom

    RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
    FileChannel inChannel = aFile.getChannel();
  2. 在 JDK 1.7 中的 NIO.2 針對各個通道提供了靜態方法 open()異步

    FileChannel inChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ)

    StandardOpenOption爲一個enum類型,常見的文件操做方式有如下幾種:工具

    public enum StandardOpenOption implements OpenOption {
        READ,   // 讀
        WRITE,  // 寫
        APPEND, // 追加
        CREATE, // 沒有新建,有就覆蓋
        CREATE_NEW, // 沒有就新建,有就報錯
    }
  3. 在 JDK 1.7 中的 NIO.2 的 Files 工具類的 newByteChannel()code

    SeekableByteChannel channel = Files.newByteChannel(Paths.get("1.png"), StandardOpenOption.READ);

基本的 Channel 示例

下面是一個使用FileChannel讀取數據到Buffer中的示例:blog

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
    System.out.println("Read " + bytesRead);
    buf.flip();

    while(buf.hasRemaining()){
        System.out.print((char) buf.get());
    }

    buf.clear();
    bytesRead = inChannel.read(buf);
}
aFile.close();

注意 buf.flip() 的調用,首先讀取數據到 Buffer,而後反轉 Buffer,接着再從 Buffer 中讀取數據。下一節會深刻講解 Buffer 的更多細節。

轉載自併發編程網 – ifeve.com,本文連接地址: Java NIO系列教程(二) Channel

相關文章
相關標籤/搜索