使用多线程实现文件的复制功能,并在控制台显示复制的进度,进度以百分比表示。例如:把文件A复制到E盘某文件夹下,在控制台上显示“文件已复制10%”,“文件已复制20%”……“文件已复制100%”,“复制

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


public class CopyFile extends Thread {


public File src;//源文件路径
public File dest;//复制目标路径

public CopyFile(String src,String dest) {
this.src = new File(src);
this.dest = new File(dest);
}

@Override
public void run() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(src);
fos = new FileOutputStream(dest);

byte[] b = new byte[1024];//声明一个字节数组,每次读取的数据存到该字节数组里
int length=0;//返回每次读取的数据长度

long len = src.length();//获取源文件的长度

double temp = 0;

DecimalFormat df = new DecimalFormat("##%");

while((length=fis.read(b))!=-1){
fos.write(b, 0, length);//把每次读取的内容,输出到目标路径文件中
temp+=length;//把每次读取的数据长度累加
double d = temp/len;//计算出已经读取的长度占文件总长度的比率
int jd = (int) d;
if(jd%10==0){
System.out.println(src.getName()+"文件复制了:"+df.format(d));
}
}

System.out.println(src.getName()+"复制完毕!");

} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}


}





}

//测试部分

public class CopyTest {


public static void main(String[] args) {
CopyFile cf1 = new CopyFile("E:\\a.txt","F:\\a.txt");
CopyFile cf2 = new CopyFile("E:\\b.txt","F:\\b.txt");
CopyFile cf3 = new CopyFile("E:\\c.txt","F:\\c.txt");
// CopyFile cf4 = new CopyFile("E:\\d.txt","F:\\d.txt");
// CopyFile cf5 = new CopyFile("E:\\e.txt","F:\\e.txt");
// CopyFile cf6 = new CopyFile("E:\\java.wmv","F:\\java.wmv");
cf1.start();
cf2.start();
cf3.start();
// cf4.start();
// cf5.start();
// cf6.start();


}


}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值