Java Nio 简明教程
Java NIO - Channels
Description
顾名思义,管道用作从一端到另一端的数据流方式。此处在 Java NIO 中,管道在缓冲区和另一端的一个实体之间起着同样的作用,换句话说,管道用于将数据读入缓冲区并从缓冲区写入数据。
As name suggests channel is used as mean of data flow from one end to other.Here in java NIO channel act same between buffer and an entity at other end in other words channel are use to read data to buffer and also write data from buffer.
与在传统 Java IO 中使用的流不同,管道是双向的,即既可以读取又可以写入。Java NIO 管道既支持阻塞模式,也支持非阻塞模式下的异步数据流。
Unlike from streams which are used in conventional Java IO channels are two way i.e can read as well as write.Java NIO channel supports asynchronous flow of data both in blocking and non blocking mode.
Implementations of Channel
Java NIO 管道主要在以下类中实现 −
Java NIO channel is implemented primarily in following classes −
-
FileChannel − In order to read data from file we uses file channel. Object of file channel can be created only by calling the getChannel() method on file object as we can’t create file object directly.
-
DatagramChannel − The datagram channel can read and write the data over the network via UDP (User Datagram Protocol).Object of DataGramchannel can be created using factory methods.
-
SocketChannel − The SocketChannel channel can read and write the data over the network via TCP (Transmission Control Protocol). It also uses the factory methods for creating the new object.
-
ServerSocketChannel − The ServerSocketChannel read and write the data over TCP connections, same as a web server. For every incoming connection a SocketChannel is created.
Example
以下示例从 C:/Test/temp.txt 的文本文件中读取数据,并将内容打印到控制台。
Following example reads from a text file from C:/Test/temp.txt and prints the content to the console.
ChannelDemo.java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelDemo {
public static void main(String args[]) throws IOException {
RandomAccessFile file = new RandomAccessFile("C:/Test/temp.txt", "r");
FileChannel fileChannel = file.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
while (fileChannel.read(byteBuffer) > 0) {
// flip the buffer to prepare for get operation
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
System.out.print((char) byteBuffer.get());
}
}
file.close();
}
}