NIO学习笔记二(Channels)
这一章主要是对NIO的Channels进行说明。
1、Channels与IO Stream的区别。
主要区别如下:
Channels是双向的,同时支持读和写数据;IO Stream是单向的,要么是读,要么是写。Channels是非阻塞的,读写支持异步;IO Stream是阻塞的;Channel将数据读入Buffer,从Buffer写入数据到Channel;2、Channel 主要实现。
?主要实现类如下:
FileChannel:支持从文件读写数据。DatagramChannel:支持从UDP协议读写数据。SocketChannel:支持从TCP协议读写数据。ServerSocketChannel:监听所有的TCP请求连接,连接成功,将会创建一个SocketChannel。3、Channel 的简单例子。
以下是使用Channel读取文件内容的简单例子:
public static void readFile(String filePath) throws IOException {//get FileChannelRandomAccessFile aFile = new RandomAccessFile(filePath, "rw");FileChannel inChannel = aFile.getChannel();//initial ByteBuffer。ByteBuffer buf = ByteBuffer.allocate(48); //read data into Buffer int bytesRead = inChannel.read(buf);while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); //read data from Buffer。 while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();}
?