JAVA中channel的transferTo方法限制

我们都知道nio中传送数据使用channel+buffer,大的数据可以使用allocateDirect申请直接内存传输以提高效率。

@Test
    public void testNIOFile() {
        long start = System.currentTimeMillis();
        try (FileInputStream is = new FileInputStream("D:\\CCleaner\\CCleaner.exe");
             FileOutputStream os = new FileOutputStream("C:/test.exe");
             FileChannel ic = is.getChannel();
             FileChannel oc = os.getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 1024);
            ic.read(buffer);
            buffer.flip();
            oc.write(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("传输完成" + (System.currentTimeMillis() - start));
    }

而NIO包中还提供了更简便的方法,就是channel的transferTo和transferFrom方法

@Test
public void testTransferTo() {
    TimeUtil.start();
    try (FileInputStream fis = new FileInputStream("F:\\test\\x64q.rpf");
         FileOutputStream fos = new FileOutputStream("F:\\x64q.rpf");
         FileChannel isc = fis.getChannel();
         FileChannel osc = fos.getChannel();
    ) {
        isc.transferTo(0,isc.size(),osc);
//            osc.transferFrom(isc,0, isc.size());
    } catch (Exception e) {
        e.printStackTrace();
    }
    TimeUtil.end();
}

而测试大文件时发现TransferTo的对象如果大于2GB的话,只会传送2GB,导致数据丢失,而TransferFrom不会出现这个情况,找资料发现使用while可以传送完,具体原因看这个博客:使用transferTo方法限制文件传输大小的原因分析_狗灬的博客-CSDN博客_transferto 大小

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值