zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java-实现文件拷贝的三种方式

JAVA文件 实现 方式 三种 拷贝
2023-06-13 09:14:21 时间
    /**
     * 文件拷贝,利用字节流批量读取实现复制文件
     * @Author: www.itze.cn
     * @Date: 2020/9/24 10:29
     * @Email: 814565718@qq.com
     * @param srcFile
     * @param destFile
     */
    public static void copyFile(File srcFile, File destFile) {
        //判断原文件是否存在
        if (!srcFile.exists()) {
            throw new IllegalArgumentException("源文件:" + srcFile + "不存在!");
        }
        //判断原文件是否为一个文件
        if (!srcFile.isFile()) {
            throw new IllegalArgumentException(srcFile + "不是一个文件!");
        }
        try {
            FileInputStream in = new FileInputStream(srcFile);
            FileOutputStream out = new FileOutputStream(destFile);
            /**
             * 读取原文件,以字节流的形式读到byte数组,1024个字节=1KB
             * 循环读取
             * in.read()读到bytes数组中,位置从0-bytes.length
             */
            byte[] bytes = new byte[10 * 1024];
            int b;  //b为读取到的字节长度
            while ((b = in.read(bytes, 0, bytes.length)) != -1) {
                //写入
                out.write(bytes, 0, b);
                out.flush();
            }
            //关闭
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件拷贝,利用带缓冲区的字节流
     * @Author: www.itze.cn
     * @Date: 2020/9/24 10:29
     * @Email: 814565718@qq.com
     * @param srcFile
     * @param destFile
     */
    public static void copyFileByBuffer(File srcFile,File destFile){
        //判断原文件是否存在
        if (!srcFile.exists()) {
            throw new IllegalArgumentException("源文件:" + srcFile + "不存在!");
        }
        //判断原文件是否为一个文件
        if (!srcFile.isFile()) {
            throw new IllegalArgumentException(srcFile + "不是一个文件!");
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
            int b;
            while ((b=bis.read())!=-1){
                bos.write(b);
                bos.flush();//刷新缓冲区,利用带缓冲区的一定要刷新缓冲区,不然无法写入
            }
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

使用方法

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        copyFile(new File("D:\\D.zip"), new File("D:\\a.zip"));  //耗时:29毫秒
        copyFileByBuffer(new File("D:\\D.zip"), new File("D:\\a.zip"));  //耗时:42900毫秒
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+(end-start)+"毫秒");
    }

第三种拷贝的方法就是,即不带缓冲区,也不使用批量读取,就是一个一个字节的读取,这种方式效率是最低的,我就不拿实例测试了。:laughing:

实际测试拷贝同一个文件,通过字节流的批量读取的方式速度是最快的。