鍍金池/ 教程/ Java/ Java NIO通道
Java NIO選擇器
Java NIO ServerSocketChannel
Java NIO通道FileLock
Java NIO組件
Java NIO編碼和解碼
Java NIO包
Java NIO緩沖區(qū)
Java NIO教程
Java NIO SocketChannel
Java NIO時間服務(wù)器示例
Java NIO字符集
Java NIO通道之間的數(shù)據(jù)傳輸
Java NIO通道
Java IO與NIO比較
Java NIO管道
Java NIO分散/聚集或向量I/O

Java NIO通道

在Java NIO中,通道是用于在實體和字節(jié)緩沖區(qū)之間有效傳輸數(shù)據(jù)的介質(zhì)。它從一個實體讀取數(shù)據(jù),并將其放在緩沖區(qū)塊中以供消費。

通道作為Java NIO提供的網(wǎng)關(guān)來訪問I/O機制。 通常,通道與操作系統(tǒng)文件描述符具有一對一關(guān)系,用于提供平臺獨立操作功能。

讓我們來看看java.nio.channels類的層次結(jié)構(gòu):

上述通道可以用于阻塞或非阻塞模式,但是我們主要關(guān)注在非阻塞模式下使用通道。

NIO通道基礎(chǔ)

通道實現(xiàn)是使用本地代碼執(zhí)行實際工作。通道接口允許我們以便攜和受控的方式訪問低級I/O服務(wù)。

在層次結(jié)構(gòu)的頂部,通道接口如下所示:

package java.nio.channels;  
 public interface Channel{  
    public boolean isclose();  
    public void Open() throws IOException;  
}

正如在上述通道接口中看到的,所有通道只有兩個常用操作:

  • 檢查通道是否關(guān)閉(isclose())
  • 打開關(guān)閉通道(close())

通道實現(xiàn)

在Java NIO中,主要使用的通道如下:

  • FileChannel:文件通道用于從文件讀取數(shù)據(jù)。它只能通過調(diào)用getChannel()方法來創(chuàng)建對象。不能直接創(chuàng)建FileChannel對象。
    下面是一個創(chuàng)建FileChannel對象的例子:
    FileInputStream fis = new FileInputStream("D:\\file-read.txt"); // Path of Input text file  
    ReadableByteChannel rbc = fis.getChannel();
    
  • DatagramChannel:數(shù)據(jù)報通道可以通過UDP(用戶數(shù)據(jù)報協(xié)議)通過網(wǎng)絡(luò)讀取和寫入數(shù)據(jù)。它使用工廠方法來創(chuàng)建新對象。
    下面是打開DatagramChannel的語法:
    DatagramChannel ch = DatagramChannel.open();
    
    用于關(guān)閉DatagramChannel的語法:
    DatagramChannel ch = DatagramChannel.close();
    
  • SocketChannel:數(shù)據(jù)報通道可以通過TCP(傳輸控制協(xié)議)通過網(wǎng)絡(luò)讀取和寫入數(shù)據(jù)。 它還使用工廠方法來創(chuàng)建新對象。
    用于打開SocketChannel的語法:
    SocketChannel ch = SocketChannel.open();  
    ch.connect(new InetSocketAddress("somehost", someport));
    
    用于關(guān)閉SocketChannel的語法:
    SocketChannel ch = SocketChannel.close();  
    ch.connect(new InetSocketAddress("somehost", someport));
    
  • ServerSocketChannelServerSocketChannel允許用戶監(jiān)聽傳入的TCP連接,與Web服務(wù)器相同。對于每個傳入連接,都會為連接創(chuàng)建一個SocketChannel。
    下面是打開ServerSocketChannel的語法:
    ServerSocketChannel ch = ServerSocketChannel.open();  
    ch.socket().bind (new InetSocketAddress (somelocalport));
    
    下面是關(guān)閉ServerSocketChannel的語法:
    ServerSocketChannel ch = ServerSocketChannel.close();  
    ch.socket().bind (new InetSocketAddress (somelocalport));
    

基本通道示例

下面來看看如何將數(shù)據(jù)從一個通道復(fù)制到另一個通道或從一個文件復(fù)制到另一個文件的示例:

package com.yiibai;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class ChannelDemo {
    public static void main(String args[]) throws IOException {
        String relativelyPath = System.getProperty("user.dir");
        FileInputStream input = new FileInputStream(relativelyPath + "/testin.txt");
        ReadableByteChannel source = input.getChannel();
        FileOutputStream output = new FileOutputStream(relativelyPath + "/testout.txt");
        WritableByteChannel destination = output.getChannel();
        copyData(source, destination);
        source.close();
        destination.close();
        System.out.println("Copy Data finished.");
    }

    private static void copyData(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(20 * 1024);
        while (src.read(buffer) != -1) {
            // The buffer is used to drained
            buffer.flip();
            // keep sure that buffer was fully drained
            while (buffer.hasRemaining()) {
                dest.write(buffer);
            }
            buffer.clear(); // Now the buffer is empty, ready for the filling
        }
    }
}

執(zhí)行上面示例代碼,得到以下結(jié)果:

Copy Data finished.

上述程序?qū)⑽谋疚募?code>filein.txt的內(nèi)容復(fù)制到另一個文本文件fileout.txt。


上一篇:Java NIO教程下一篇:Java NIO SocketChannel