题目描述:
- 实现文件复制功能
- 多线程实现文件从一个目录复制到另一个目录
- @param sourceFile : 给定源文件路径名
- @param desPath : 复制点文件路径
代码:
package fileio20180924;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.omg.CORBA.PUBLIC_MEMBER;
/**
* 实现文件复制功能
* 多线程实现文件从一个目录复制到另一个目录
* @param sourceFile : 给定源文件路径名
* @param desPath : 复制点文件路径
* @author Cue
*
*/
public class FileCopy extends Thread {
private File sourceFile;//待读取的源文件
private File desPath;//待写入的目标文件
public FileCopy(String sourceFile,String desPath){
this.sourceFile = new File(sourceFile);
this.desPath = new File(desPath);
}
public void run(){
FileInputStream in = null;
FileOutputStream out = null;
try{
in = new FileInputStream(sourceFile);
out = new FileOutputStream(desPath);
byte[] b = new byte[1024];
int length = 0;
//获取源文件大小
long len = sourceFile.length();
//已复制文件的字节数
double temp = 0;
//数字格式化,显示百分比
DecimalFormat dFormat = new DecimalFormat("##.00%");
while((length = in.read(b)) != -1){
//输出字节
out.write(b, 0, length);
//获取已下载的大小,并且转换成百分比
temp += length;
double d = temp/len;
System.out.println(sourceFile.getName() + "已复制的进度 :"+dFormat.format(d));
}
System.out.println(sourceFile.getName() + "复制完成!");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(in != null){
in.close();
}
if(out != null){
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FileCopy cf = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\1.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\11.txt");
FileCopy cf2 = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\2.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\22.txt");
FileCopy cf3 = new FileCopy("C:\\Users\\小玉沉香\\Desktop\\source\\3.txt","C:\\Users\\小玉沉香\\Desktop\\desPath\\33.txt");
cf.start();
cf2.start();
cf3.start();
}
}
输出结果: