NIO-学习
通道(Channel)
通道表示打开到 IO 设备(例如:文件、套接字)的连接。若需要使用 NIO 系统,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。Channel 负责传输, Buffer 负责存储。通道是由 java.nio.channels 包定义的。 Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据, Channel 只能与Buffer 进行交互。
通道都是操作缓存区完成全部的功能的。
Java中所有已知 Channel 实现类:
- AbstractInterruptibleChannel
- AbstractSelectableChannel
- DatagramChannel
- FileChannel
- Pipe.SinkChannel
- Pipe.SourceChannel
- SelectableChannel
- ServerSocketChannel
- SocketChannel
常用的有入下几个:
- FileChannel:用于读取、写入、映射和操作文件的通道。
- DatagramChannel:通过 UDP 读写网络中的数据通道。
- SocketChannel:通过 TCP 读写网络中的数据。
- ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。
获取通道
获取通道的一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下:
- FileInputStream
- FileOutputStream
- RandomAccessFile
- DatagramSocket
- Socket
- ServerSocket
获取通道的其他方式是使用 Files 类的静态方法 newByteChannel() 获取字节通道。或者通过通道的静态方法 open() 打开并返回指定通道。
FileChannel
- 为了更形象解释说明的Channel,下面准备以FileChannel的一些简单代码进行说明就容易懂了。
- 准备以FileOutputStream类为准,这两个类都是支持通道操作的。
String info[] = {"欢迎","关注","贝克田庄","的","博客","谢谢!!"} ; File file = new File("d:" + File.separator + "testfilechannel.txt") ; FileOutputStream output = null ; FileChannel fout = null; try { output = new FileOutputStream(file) ; fout = null; fout = output.getChannel() ; // 得到输出的通道 ByteBuffer buf = ByteBuffer.allocate(1024) ; for(int i=0;i<info.length;i++){ buf.put(info[i].getBytes()) ; // 字符串变为字节数组放进缓冲区之中 } buf.flip() ; fout.write(buf) ; // 输出缓冲区的内容 } catch (Exception e) { e.printStackTrace(); }finally{ if(fout!=null){ try { fout.close() ; } catch (IOException e) { e.printStackTrace(); } } if(output!=null){ try { output.close() ; } catch (IOException e) { e.printStackTrace(); } } }