Java中的NIO详解Day05-Channel之间的数据传输

深碍√TFBOYSˉ_ 2023-02-08 15:58 147阅读 0赞

Channel之间的数据传输

  • FileChannel
  • transferFrom
  • transferTo

FileChannel

  • Java NIO中,如果两个通道中有一个是FileChannel. 那么可以直接将数据从一个channel传输到另一个channel

transferFrom

  • FileChanneltransferFrom() 方法可以将数据从给定的可读取字节文件传输到FileChannel
  • 示例:

    RandomAccessFile fromFile = new RandomAccessFile(“fromFile.txt”, “rw”);
    FileChannel fromChannel = fromFile.getChannel();

    RandomAccessFile toFile = new RandomAccessFile(“toFile.txt”, “rw”);
    FileChannel toChannel = toFile.getChannel();

    long position = 0;
    long count = fromChannel.size();

    toChannel.transferFrom(position, count, fromChannel);

  • position:position处开始向目标文件写入数据

  • count: 最多传输的字节数. 如果源通道的剩余空间小于count字节,则所传输的数据要小于请求的字节
  • SocketChannel的实现中 ,SocketChannel只会传输此刻准备好的数据,可能不足count字节.所以 ,SocketChannel可能不会将请求的所有数据,即count个字节的数据.全部传输到FileChannel

transferTo

  • FileChanneltransferTo() 方法将数据从FileChannel传输到其余的Channel
  • 示例:

    RandomAccessFile fromFile = new RandomAccessFile(“fromFile.txt”, “rw”);
    FileChannel fromChannel = fromFile.getChannel();

    RandomAccessFile toFile = new RandomAccessFile(“toFile.txt”, “rw”);
    FileChannel toChannel = toFile.getChannel();

    long position = 0;
    long count = fromChannel.size();

    fromChannel.transferTo(position, count, toChannel);

  • position:position处开始向目标文件写入数据

  • count: 最多传输的字节数. 如果源通道的剩余空间小于count字节,则所传输的数据要小于请求的字节
  • SocketChannel的实现中 ,SocketChannel只会传输此刻准备好的数据,可能不足count字节.所以 ,SocketChannel可能不会将请求的所有数据,即count个字节的数据.全部传输到FileChannel

发表评论

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

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

相关阅读