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

  • 相关阅读:
    C# 中使用反射的优缺点
    winfrom---Window 消息大全
    Entity Framework:三种开发模式实现数据访问
    asp.net Core 2.0 MVC为Controller或Action添加定制特性实现登录验证
    [十二省联考2019] 异或粽子 解题报告 (可持久化Trie+堆)
    [jzoj 3175] 数树数 解题报告 (树链剖分)
    [jzoj 5661] 药香沁鼻 解题报告 (DP+dfs序)
    [jzoj 5662] 尺树寸泓 解题报告 (线段树+中序遍历)
    [jzoj 5664] [GDOI2018Day1模拟4.6] 凫趋雀跃 解题报告(容斥原理)
    范德蒙恒等式学习笔记
  • 原文地址:https://www.cnblogs.com/binarylei/p/9977466.html
Copyright © 2011-2022 走看看