JAVA 文件下载复制百分比进度计算公式

百分比进度= 每次读写的长度 *100/需要复制文件总长度 

下载文件计算百分比进度同理

 

  public void copyFile(String oldPath, String newPath, FileProgress fileProgress) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            File newFile = new File(newPath);
            if (newFile.exists()) {
                newFile.delete();
            }
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                long length = oldfile.length();
                fileProgress.start();
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
         //i=已复制文件百分比进度;bytesum = 每次读写的累加的长度;length =需要复制文件的总长度
                    long i = bytesum * 100 / length;
                    System.out.println("百分比进度" + i);
                    fs.write(buffer, 0, byteread);
                    fileProgress.running(i);
                }
                inStream.close();
            }
            fileProgress.stop(newPath);
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
            fileProgress.error(e);

        }

    }

    interface FileProgress {
        void start();//开始回调

        void running(long i);//进度百分比

        void stop(String filePath);//成功后文件的路径

        void error(Exception e);//错误信息
    }

使用:上面封装的方法没有做回调判空处理,传null给回调参数会崩。回调参数一定要传。不传的去封装的方法加个判空,异常记得补个finally关掉流不然会泄露

copyFile("需要复制文件的路径", "复制到哪里的路径", new FileProgress() {

            @Override
            public void start() {
                //开始复制时的回调
            }

            @Override
            public void running(int i) {
                //复制过程中的回调 i=百分比进度

            }

            @Override
            public void stop(String filePath) {
                //完成时的回调

            }

            @Override
            public void error(Exception e) {
               //出错时的回调

            }
        });

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值