Java 使用 Channel 与 Buffer 实现文件快速拷贝

代码如下:

先演示先 Buffer 的使用,代码如下:

    public static void main1(String[] args) {
        IntBuffer allocate = IntBuffer.allocate(5);
        allocate.put(30);
        allocate.put(34);

        Buffer flip = allocate.flip();

        while (flip.hasRemaining()) {
            System.out.println(allocate.get());
        }
    }

方法一:Java 使用 Channel 通道实现快速拷贝文件方法:

    public static void main222(String[] args) throws Exception {
            FileInputStream fileInputStream = new FileInputStream("/Users/Desktop/file.txt");
            FileChannel sourceChannel = fileInputStream.getChannel();

            FileOutputStream fileOutputStream = new FileOutputStream("/Users/Desktop/file4.txt");
            FileChannel destChannel = fileOutputStream.getChannel();

            // destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            sourceChannel.transferTo(0, sourceChannel.size(), destChannel);

            fileInputStream.close();
            fileOutputStream.close();
    }

transferTo() 方法底层使用了 零拷贝 方法提升了性能

方法二:ByteBuffer + Channel 结合的方式实现文件拷贝

    public static void main11(String[] args) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("/Users/gongweiming/Desktop/file.txt");
            FileChannel channel = fileInputStream.getChannel();


            FileOutputStream fileOutputStream = new FileOutputStream("/Users/gongweiming/Desktop/file2.txt");
            FileChannel outChannel = fileOutputStream.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            while (true) {
                // 注意必须复位 Position Limit,否则 len 永远返回 0,因为 Postion 和 limit 相等
                byteBuffer.clear();
                int len = channel.read(byteBuffer);
                if (len == -1) {
                    break;
                }
                // 反转
                byteBuffer.flip();
                outChannel.write(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔道不误砍柴功

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值