使用多线程实现多个文件同步复制功能,并在控制台显示复制的进度,进度以百分比表示
测试类
public class Test2 {
public static void main ( String[ ] args) {
Thread t = new Thread ( new CopyFileThread ( "E:\\JDK_API_1_6_zh_CN.CHM" , "E:\\temp\\JDK_API_1_6_zh_CN.CHM" ) ) ;
t. start ( ) ;
System. out. println ( ) ;
Thread t1 = new Thread ( new CopyFileThread ( "E:\\Lj\\QQ_PCDownload1100109932.exe" , "E:\\temp\\QQ_PCDownload1100109932.exe" ) ) ;
t1. start ( ) ;
}
}
CopyFileThread类
public class CopyFileThread implements Runnable {
private String srcFile;
private String destFile;
public CopyFileThread ( ) { }
public CopyFileThread ( String srcFile, String destFile) {
this . srcFile = srcFile;
this . destFile = destFile;
}
@Override
public void run ( ) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream ( srcFile) ;
fos = new FileOutputStream ( destFile) ;
DecimalFormat df = new DecimalFormat ( "##%" ) ;
File file = new File ( srcFile) ;
long length = file. length ( ) ;
double total = 0 ;
int len;
int a = 1 ;
byte [ ] b = new byte [ 1024 ] ;
while ( ( len = fis. read ( b) ) != - 1 ) {
fos. write ( b, 0 , len) ;
total += len;
if ( total > length/ 10 * a) {
System. out. println ( df. format ( ( double ) total/ length) ) ;
a++ ;
}
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}