NIO之通道Channel【FileChannel介绍】

约定不等于承诺〃 2022-04-24 00:44 383阅读 0赞

通道(channel)介绍

  Channel是一个对象,作用是用于源节点和目标节点的连接,在java NIO中负责缓冲区数据的传递。Channel本身不存储数据,因此需要配合缓冲区进行传输。

在这里插入图片描述

主要的实现类有

  主要的实现类有如下四个: FileChannel, SocketChannel, ServerSocketChannel, DatagramChannel,都实现了java.nio.channels.Channel接口
在这里插入图片描述

获取通道

  1. Java针对支持通道的类提供了getChannel()方法





















本地IO 网络IO
FileInputStream/FileOutputStream Socket
RandomAccessFile ServerSocket
DatagramSocket
  1. 在JDK1.7中的NIO.2针对各个通道提供了静态方法open()
  2. 在JDK1.7中的NIO.2的Files工具类的newByteChannel()

    public static void main(String[] args) throws Exception {

    1. // 1本地IO获取通道
    2. FileInputStream in = new FileInputStream("c:/tools/a.txt");
    3. FileChannel fileChannel = in.getChannel();
    4. // 2.通过open方法获取
    5. FileChannel.open(Paths.get("c:/tools/a.txt"), StandardOpenOption.READ);

    }

案例-文件复制

1.使用FileChannel配合缓冲区实现文件复制的功能

  1. /** * FileChannel实现文件复制功能 * @param args * @throws Exception */
  2. public static void main(String[] args) throws Exception {
  3. FileInputStream in = new FileInputStream("c:/tools/a.txt");
  4. FileOutputStream out = new FileOutputStream("c:/tools/a-copy1.txt");
  5. FileChannel inChannel = in.getChannel();
  6. FileChannel outChannel = out.getChannel();
  7. // 分配指定大小的缓冲区
  8. ByteBuffer bb = ByteBuffer.allocate(1024);
  9. // 将通道中的数据存入缓冲区中
  10. while(inChannel.read(bb)!=-1){
  11. bb.flip();// 切换到读取模式
  12. outChannel.write(bb); // 将缓冲区的数据写入到输出通道中
  13. bb.clear(); // 清空缓冲区
  14. }
  15. outChannel.close();
  16. inChannel.close();
  17. }

2.内存映射文件的方式实现文件复制

  1. /** * 使用直接缓冲区来完成文件的复制【内存映射文件】 * @param args * @throws Exception */
  2. public static void main(String[] args) throws Exception {
  3. FileChannel inChannel = FileChannel.open(Paths.get("c:/tools/a.txt"),StandardOpenOption.READ );
  4. FileChannel outChannel = FileChannel.open(
  5. Paths.get("c:/tools/aa.txt")
  6. , StandardOpenOption.WRITE
  7. ,StandardOpenOption.CREATE
  8. ,StandardOpenOption.READ);
  9. // 获取内存映射文件
  10. MappedByteBuffer inMap = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
  11. MappedByteBuffer outMap = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
  12. byte[] b = new byte[inMap.limit()];
  13. // 从磁盘文件中获取数据写入到b字节数组中
  14. inMap.get(b);
  15. // 将b字节数组中的数据写入到磁盘文件中
  16. outMap.put(b);
  17. inChannel.close();
  18. outChannel.close();
  19. }

3.Channel-to-channel方式实现复制

  1. /** * 使用直接缓冲区来完成文件的复制【内存映射文件】 * @param args * @throws Exception */
  2. public static void main(String[] args) throws Exception {
  3. FileChannel inChannel = FileChannel.open(Paths.get("c:/tools/a.txt"),StandardOpenOption.READ );
  4. FileChannel outChannel = FileChannel.open(
  5. Paths.get("c:/tools/aa1.txt")
  6. ,StandardOpenOption.WRITE
  7. ,StandardOpenOption.CREATE
  8. ,StandardOpenOption.READ);
  9. //Channel-to-channel 传输是可以极其快速的,特别是在底层操作系统提供本地支持的时候。某些
  10. //操作系统可以不必通过用户空间传递数据而进行直接的数据传输。对于大量的数据传输,这会是一个巨大的帮助
  11. inChannel.transferTo(0, inChannel.size(), outChannel);
  12. inChannel.close();
  13. outChannel.close();
  14. }

scatter和gather

分散(scatter)

  从Channel中读取是指在读操作时将读取的数据写入多个buffer中,将从Channel中读取的数据“分散(scatter)”到多个Buffer中

在这里插入图片描述

  1. /** * 分散:scatter * @param args * @throws IOException */
  2. public static void main(String[] args) throws IOException {
  3. FileChannel channel = FileChannel.open(Paths.get("c:/tools/a.txt"), StandardOpenOption.READ);
  4. // TODO Auto-generated method stub
  5. ByteBuffer header = ByteBuffer.allocate(16);
  6. ByteBuffer body = ByteBuffer.allocate(1024);
  7. ByteBuffer[] bufferArray = { header, body };
  8. channel.read(bufferArray);
  9. bufferArray[0].flip();
  10. bufferArray[1].flip();
  11. System.out.println(new String(bufferArray[0].array(),0,bufferArray[0].limit()));
  12. System.out.println("---------");
  13. System.out.println(new String(bufferArray[1].array(),0,bufferArray[1].limit()));
  14. }

注意buffer首先被插入到数组,然后再将数组作为channel.read() 的输入参数。read()方法按照buffer在数组中的顺序将从channel中读取的数据写入到buffer,当一个buffer被写满后,channel紧接着向另一个buffer中写。
Scattering Reads在移动下一个buffer前,必须填满当前的buffer,这也意味着它不适用于动态消息(译者注:消息大小不固定)。换句话说,如果存在消息头和消息体,消息头必须完成填充(例如 128byte),Scattering Reads才能正常工作。

聚集(gather)

  写入Channel是指在写操作时将多个buffer的数据写入同一个Channel, 将多个Buffer中的数据“聚集(gather)”后发送到Channel

在这里插入图片描述

  1. /** * 聚集gether * @param args * @throws IOException */
  2. public static void main(String[] args) throws IOException {
  3. FileChannel channel = FileChannel.open(Paths.get("c:/tools/ag.txt"), StandardOpenOption.WRITE);
  4. ByteBuffer header = ByteBuffer.allocate(128);
  5. ByteBuffer body = ByteBuffer.allocate(1024);
  6. // 写入内容
  7. header.put("bobo".getBytes());
  8. // 转换为读模式
  9. header.flip();
  10. // 写入内容
  11. body.put("hello".getBytes());
  12. // 转换为读模式
  13. body.flip();
  14. //write data into buffers
  15. ByteBuffer[] bufferArray = { header, body };
  16. // 将这两个缓冲区的数据依次写入到文件中
  17. channel.write(bufferArray);
  18. }

buffers数组是write()方法的入参,write()方法会按照buffer在数组中的顺序,将数据写入到channel,注意只有position和limit之间的数据才会被写入。因此,如果一个buffer的容量为128byte,但是仅仅包含58byte的数据,那么这58byte的数据将被写入到channel中。因此与Scattering Reads相反,Gathering Writes能较好的处理动态消息。

发表评论

表情:
评论列表 (有 0 条评论,383人围观)

还没有评论,来说两句吧...

相关阅读