在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)注在非阻塞模式下使用通道。
通道實現(xiàn)是使用本地代碼執(zhí)行實際工作。通道接口允許我們以便攜和受控的方式訪問低級I/O服務(wù)。
在層次結(jié)構(gòu)的頂部,通道接口如下所示:
package java.nio.channels;
public interface Channel{
public boolean isclose();
public void Open() throws IOException;
}
正如在上述通道接口中看到的,所有通道只有兩個常用操作:
isclose()
)close()
)在Java NIO中,主要使用的通道如下:
getChannel()
方法來創(chuàng)建對象。不能直接創(chuàng)建FileChannel
對象。FileChannel
對象的例子:FileInputStream fis = new FileInputStream("D:\\file-read.txt"); // Path of Input text file
ReadableByteChannel rbc = fis.getChannel();
DatagramChannel
的語法:DatagramChannel ch = DatagramChannel.open();
用于關(guān)閉DatagramChannel
的語法:DatagramChannel ch = DatagramChannel.close();
SocketChannel
的語法:SocketChannel ch = SocketChannel.open();
ch.connect(new InetSocketAddress("somehost", someport));
用于關(guān)閉SocketChannel
的語法:SocketChannel ch = SocketChannel.close();
ch.connect(new InetSocketAddress("somehost", someport));
ServerSocketChannel
允許用戶監(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
。