NIO的channel

本文介绍了Java NIO中的Channel概念,强调其双向读写特性,并对比了它与传统对象的区别。通过示例展示了如何使用FileChannel进行文件内容的复制,包括`transferFrom`和`transferTo`方法的运用,帮助理解Channel与Buffer的交互操作。
摘要由CSDN通过智能技术生成

一 channel

1.1 channel概念

流的读写通常是单向的。通道是双向的,可以用于读、写和同时读写操作,通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。从通道读取数据到缓冲区,从缓冲区写入数据到通道

 1.2 channel与传统对象的区别

1、 Channel可以直接将指定文件的部分或全部直接映射成Buffer。
2、 程序不能直接访问Channel中的数据,包括读、写入都不行 Channel只能与Buffer进行交互 。也就是说, 如果要从Channel中取得数据,必须先用Buffer从Channel中取出一些数据,然后让程序从Buffer中取出这些 数据;如果要将程序中的数据写入Channel,一样先让程序将谁放入Buffer中,程序再将Buffer里的数据写入Channel中。

二 channel的操作案例

1.fromFileChannel

将d盘的内容复制到e盘

      RandomAccessFile fromFile = new RandomAccessFile("d:/testbuffer.txt", "rw");
        FileChannel fromFileChannel = fromFile.getChannel();

        RandomAccessFile toFile = new RandomAccessFile("E:/liu.txt", "rw");
        FileChannel toFileChannel = toFile.getChannel();

        long position = 0;
        long count = fromFileChannel.size();
        toFileChannel.transferFrom(fromFileChannel, position, count);

2.transferTo

    public static void fileChannel() throws Exception {
        RandomAccessFile fromFile = new RandomAccessFile("d:/testbuffer.txt", "rw");
        FileChannel fromFileChannel = fromFile.getChannel();

        RandomAccessFile toFile = new RandomAccessFile("E:/li.txt", "rw");
        FileChannel toFileChannel = toFile.getChannel();

        long position = 0;
        long count = fromFileChannel.size();
        //toFileChannel.transferFrom(fromFileChannel, position, count);//将d盘内容复制到e盘
        fromFileChannel.transferTo(position, count, toFileChannel);//将d盘内容复制到e盘
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值