zoukankan      html  css  js  c++  java
  • IO文件复制的三种方法

    FileChannel实现文件复制
    // 1、当文件大小小于2GB时,这种方式没有什么大问题,但是如果文件小大超过2GB,这种方式就会数据丢失
    // 测试文件大小:8832KB
    public static void ioOption() throws IOException {
     
        // 文件输入流通道
        FileChannel inputChannel = new FileInputStream(new File("D:/demo.txt")).getChannel();
        // 文件输出流通道
        FileChannel outputChannel = new FileOutputStream(new File("D:/copy.txt")).getChannel();
        // 数据转移
        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
     
        inputChannel.close();
        outputChannel.close();
    }
    输出:
    耗时(毫秒):10
     
    // 2、当文件大小超过2GB时处理办法
    // 测试文件大小:8832KB
    public static void ioOption() throws IOException {
     
        // 文件输入流通道
        FileChannel inputChannel = new FileInputStream(new File("D:/demo.txt")).getChannel();
        // 文件输出流通道
        FileChannel outputChannel = new FileOutputStream(new File("D:/copy.txt")).getChannel();
     
        // 文件转移起始位置,默认0
        long position  = 0;
        // 文件长度
        long size  = inputChannel.size();
        // 数据转移
        // count 转移的字节数
        long count = inputChannel.transferTo(position, size, outputChannel);
        // 循环方式,转移数据
        // 比如:
        // 文件长度为220,但是一次只能转移100;position = 0,size = 220
        // 100 < 220,
        // 第二次从100开始,转移长度为120;position = 100,size = 120
        // 100 < 120,
        // 第三次从200开始,转移长度为20;position = 200,size = 20
        // 20 = 20
        // 退出循环,转移完毕
        while(count < size){
            position += count;
            size -= count;
            count = inputChannel.transferTo(position, size, outputChannel);
        }
     
        inputChannel.close();
        outputChannel.close();
    }
    传统IO方式文件复制
    3.
    // 测试文件大小:8832KB
    public static void ioOption4() throws IOException {
     
        // 获取文件 字节输入流,如果文件不存在抛出异常
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("D:/demo.txt")));
        // 获取文件 字节输出流,如果文件不存在自动创建文件
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/copy.txt")));
        // 字节数组
        byte[] bytes = new byte[1024];
     
        int len = 0;
        // 一次读取一个 bytes 大小的数据
        // len 表示读取到的字节数,如果没有数据则返回 -1
        while ((len = bis.read(bytes))!= -1){
            bos.write(bytes,0,len);
        }
     
        bis.close();
        bos.close();
    }
    输出:
    耗时(毫秒):22

    面向通道缓存的效率是面向流的的两倍
  • 相关阅读:
    javascript获取当前日期、年份和月份等
    程序员也可以懂一点期望值管理
    数据类型,隐式转换以及json,对象,引用类型,预解析 视频教程
    两个值交互位置的几种方法
    通过Class获取标签,兼容的几种思路
    前端开发流程
    元素多层嵌套,JS获取问题
    原生JS实现分页效果2.0(新增了上一页和下一页,添加当前元素样式)
    原生JS实现分页效果1.0
    学习方法,以及时间的安排。
  • 原文地址:https://www.cnblogs.com/wl889490/p/12724615.html
Copyright © 2011-2022 走看看