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

  • 相关阅读:
    HTML5结构
    HTML5新增的非主体元素header元素、footer元素、hgroup元素、adress元素
    CF GYM 100703G Game of numbers
    CF GYM 100703I Endeavor for perfection
    CF GYM 100703K Word order
    CF GYM 100703L Many questions
    CF GYM 100703M It's complicate
    HDU 5313 Bipartite Graph
    CF 560e Gerald and Giant Chess
    POJ 2479 Maximum sum
  • 原文地址:https://www.cnblogs.com/binarylei/p/9977466.html
Copyright © 2011-2022 走看看