栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
            }
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036124.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号