简单的Android下的拷贝文件单线程工具类

这个博客介绍了一个用于拷贝视频文件的工具类,该类在Android环境中实现,能够显示拷贝进度。通过FileInputStream和FileOutputStream进行文件读写,并使用DecimalFormat格式化进度显示。虽然代码中没有实现MD5校验,但提示可以在完成时添加这一功能以确保文件完整无误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目涉及到视频文件的拷贝操作,提供一个工具类的轮子以供使用

package com.lanky.videobanner.utils;

import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

import static com.lanky.videobanner.GlobalInfo.Constants.TAG;

public class CopyFileThread extends Thread {
    private File sourceFile;
    private File targetFile;

    public CopyFileThread(String sourceFilePath, String targetFilePath) {
        this.sourceFile = new File(sourceFilePath);
        this.targetFile = new File(targetFilePath);
    }

    public void run() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(targetFile);
            byte[] b = new byte[1024];
            int a;
            long len = sourceFile.length();
            double temp = 0;
            DecimalFormat df = new DecimalFormat("##.##%");
            double progress = 0;
            while ((a = fis.read(b)) != -1) {
                fos.write(b, 0, a);
                temp += a;
                if (temp / len - progress > 0.01) {
                    progress = temp / len;
                }
                Log.d(TAG, "CopyFileThread: " + sourceFile.getName() + " has been copied by " + df.format(progress));
            }
            Log.d(TAG, "CopyFileThread: " + sourceFile.getName() + " copied finished!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fis != null;
                fis.close();
                assert fos != null;
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

可以在finish的时候添加MD5校验,自行拓展即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值