使用多线程实现多个文件同步复制功能,并在控制台显示复制的进度,进度以百分比表示。例如:把文件A复制到E盘某文件夹下,在控制台上显示“XXX文件已复制10%”,“XXX文件已复制20%”……“XXX文件已复制100%”,“XXX复制完成!”
import java.io.*;
import java.text.DecimalFormat;
public class ThreadWork3 {
public static void main(String[] args) {
CopyFiles copyFiles1 = new CopyFiles("E:\\f1.txt","E:\\f2.txt");
CopyFiles copyFiles2 = new CopyFiles("E:\\f3.txt","E:\\f4.txt");
copyFiles1.start();
copyFiles2.start();
}
}
class CopyFiles extends Thread {
private File src;//源文件
private File dest;//复制的文件
public CopyFiles(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 decimalFormat = new DecimalFormat("##.00%");//格式化,显示百分比
while ((length = fis.read(b)) != -1) {
fos.write(b, 0, length);
temp += length;
double d = temp / len;
System.out.println(src.getName() + "文件已复制" + decimalFormat.format(d));
}
System.out.println(src.getName() + "文件已经复制完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}