目录递归拷贝(java)


public class Test4 {
private static long totalSize = 0;
public static void main(String...args) throws IOException{
File f1 = new File("E:\\TDDOWNLOAD");
File f2 = new File("E:\\TDDOWNLOAD2");
long start = System.currentTimeMillis();
copy(f1, f2);
long end = System.currentTimeMillis();
System.out.println("拷贝总大小:"+totalSize*1.0/1024/1024+"(MB), time: "+(end-start));
}

public static void copy(File f1, File f2) throws IOException{
//如果目标不是目录,直接退出
if(!f2.isDirectory()){
return ;
}
//源文件是目录,循环所有子文件
if(f1.isDirectory()){
File[] subFiles = f1.listFiles();
for(int i=0;i<subFiles.length;i++){
String newFileName = f2.getPath()+"/"+subFiles[i].getName();
File newFile = new File(newFileName);
//子文件是目录则递归拷贝
if(subFiles[i].isDirectory()){
if(!newFile.exists()){
newFile.mkdir();
}else{
}
copy(subFiles[i], newFile);
}else{//子文件是文件,则直接拷贝
copy(subFiles[i],f2);
}
}
}else{//源文件是文件直接拷贝
String newFileName = f2.getPath()+"/"+f1.getName();
File newFile = new File(newFileName);
//是否覆盖拷贝
/*if(newFile.exists()){
return ;
}*/
newFile.createNewFile();
FileInputStream fis = new FileInputStream(f1);
BufferedInputStream bis = new BufferedInputStream(fis, 8192);
FileOutputStream fos = new FileOutputStream(newFileName);
BufferedOutputStream bos = new BufferedOutputStream(fos,8192);
byte[] b = new byte[8192];
int count = -1;
while((count=bis.read(b))!=-1){
totalSize+=count;
bos.write(b,0,count);
}
bis.close();
bos.close();
fis.close();
fos.close();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值