项目简介
使用一个线程实现文件拷贝,开启另一个线程计算并显示当前拷贝的进度
拷贝类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo301 extends Thread{
@Override
public void run() {
Demo302 bs = new Demo302();
bs.setDaemon(true);//设置当前线程为守护线程
bs.start();
try {
sleep(1);
copy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void copy() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File sourceFile = new File("D:\\Java\\note\\java基础\\7.20note\\video\\02_异常处理.avi");//待拷贝的文件
fis = new FileInputStream(sourceFile);
File targetDir = new File("C:\\Users\\Huaazai\\Desktop\\exp");//欲拷贝到的位置
fos = new FileOutputStream(new File(targetDir, sourceFile.getName()));
byte[] b = new byte[1014];
int len = 0;
try {
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Demo301().run();
}
}
监控进度类
import java.io.File;
import java.text.DecimalFormat;
public class Demo302 extends Thread{
@Override
public void run() {
File f1 = new File("C:\\Users\\Huaazai\\Desktop\\exp\\02_异常处理.avi");//已经拷贝了的文件
File f2 = new File("D:\\Java\\note\\java基础\\7.20note\\video\\02_异常处理.avi");//待拷贝文件
while(true){
try {
while(f1.length()<f2.length())
{
System.out.println("进度:"+ new DecimalFormat("00.0%").format(((double)f1.length()/(double)f2.length())));//大小相除获得进度,并设置进度格式
sleep(1);
if(f1.length()==f2.length()){
System.out.println("复制完成!");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
代码运行结果
两个进程同时开始,同时结束,确保进度的正确性,由于对线程的学习还不够好,代码结果处有时候会出现一些问题,希望大佬们能给点建议?