zoukankan      html  css  js  c++  java
  • Java NIO系列教程(五) 通道之间的数据传输

    Java NIO系列教程(五) 通道之间的数据传输

    在 Java NIO 中,如果两个通道中有一个是 FileChannel,那你可以直接将数据从一个 channel(译者注:channel 中文常译作通道)传输到另外一个 channel。

    一、通道的基本操作

    FileInputStream fis = new FileInputStream("1.png");
    FileOutputStream fos = new FileOutputStream("2.png");
    
    //1. 获取通道
    FileChannel inChannel = fis.getChannel();
    FileChannel outChannel = fos.getChannel();
    
    //2. 分配缓冲区
    ByteBuffer buf = ByteBuffer.allocate(1024);
    
    //3. 用通道传输数据
    while (inChannel.read(buf) != -1) {
        buf.flip();
        outChannel.write(buf);
        buf.clear();
    }
    

    二、直接缓冲区拷贝文件

    FileChannel inChannel = FileChannel.open(Paths.get("1.png"), StandardOpenOption.READ);
    FileChannel outChannel = FileChannel.open(Paths.get("3.png"), 
        StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
    
    //内存映射文件,直接缓冲区
    MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
    MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
    
    byte[] bytes = new byte[inMappedBuf.limit()];
    inMappedBuf.get(bytes);
    outMappedBuf.put(bytes);
    

    三、transferFrom() 和 transferTo()

    FileChannel 的 transferFrom() 方法可以将数据从源通道传输到 FileChannel 中(译者注:这个方法在 JDK 文档中的解释为将字节从给定的可读取字节通道传输到此通道的文件中)。下面是一个简单的例子:

    RandomAccessFile inFile = new RandomAccessFile("fromFile.txt", "rw");
    FileChannel inChannel = fromFile.getChannel();
    
    RandomAccessFile outFile = new RandomAccessFile("toFile.txt", "rw");
    FileChannel outChannel = toFile.getChannel();
    
    long position = 0;
    long count = inChannel.size();
    
    outChannel.transferFrom(position, count, inChannel);
    //inChannel.transferTo(position, count, outChannel);
    

    方法的输入参数 position 表示从 position 处开始向目标文件写入数据,count 表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。
    此外要注意,在 SoketChannel 的实现中,SocketChannel 只会传输此刻准备好的数据(可能不足 count 字节)。因此,SocketChannel 可能不会将请求的所有数据(count 个字节)全部传输到 FileChannel 中。

    转载自并发编程网 – ifeve.com,本文链接地址: Java NIO系列教程(二) Channel

  • 相关阅读:
    微信redirect_uri域名与后台配置不一致,错误代码10003
    windows安装centos7子系统
    c++中的var_dump
    egret3.x升级5.2
    PHP更改自动加载的顺序
    重定向如何携带cookie
    elasticsearch和mysql排序问题
    npm错误:Error: listen EADDRNOTAVAIL
    Spring Boot WebFlux 集成 Mongodb 数据源操作
    泥瓦匠:程序猿为啥要坚持写原创技术博客?
  • 原文地址:https://www.cnblogs.com/binarylei/p/9977466.html
Copyright © 2011-2022 走看看