JAVA实现目录拷贝(注意递归的思想)
程序员文章站
2022-10-03 18:24:44
import org.junit.Test;import java.io.*;public class copyDir { public void copyDir(File source,File target){ if(source.isFile()||!source.exists()){ return; } File newDir=new File(target,source.getName());...
import org.junit.Test;
import java.io.*;
public class copyDir {
public void copyDir(File source,File target){
if(source.isFile()||!source.exists()){
return;
}
File newDir=new File(target,source.getName());
newDir.mkdir();
File[] listFiles=source.listFiles();
for (File listFile : listFiles) {
if(listFile.isFile()){
try
{
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(listFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File(newDir,listFile.getName())));
int len=0;
byte[] bytes=new byte[1024*8];
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
bos.close();
bis.close();
}
catch (Exception e){
}
}else{
copyDir(listFile, newDir);
}
}
}
@Test
public void TestCopyDir(){
File source=new File("D:\\io\\source");
File target=new File("D:\\io\\target");
copyDir(source, target);
}
}
本文地址:https://blog.csdn.net/peacezhi/article/details/107677601