百分比进度= 每次读写的长度 *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) {
//出错时的回调
}
});