package test;
import java.util.Date;
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws FileNotFoundException {
File f1=new File("C:\\Users\\Administrator\\Desktop\\gra_design\\code");
File f2=new File("D:\\");
copyDir(f2,f1);
}
private static void copyDir(File f2,File f1) {
if (f1.isFile()) {
FileInputStream in=null;FileOutputStream out=null;
try {
in =new FileInputStream(f1.getAbsoluteFile());
out=new FileOutputStream((f2.getAbsolutePath().endsWith("\\")?f2.getAbsolutePath():f2.getAbsolutePath()+"\\")+f1.getAbsolutePath().substring(3));
int readCount=0;
byte[] b=new byte[1024*1024];
while ((readCount=in.read(b))!=-1) {
out.write(b,0,readCount);
}
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (in!=null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (out!=null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return;
//检测到f1是一个文件,那么递归就结束了
}
File[] files=f1.listFiles();
//获得目录下的全部文件
for (File file:files) {
if (file.isDirectory()) {
String srcPath=file.getAbsolutePath();
System.out.println(srcPath);
String desPath=(f2.getAbsolutePath().endsWith("\\")?f2.getAbsolutePath():f2.getAbsolutePath()+"\\")+srcPath.substring(3);
//先判断f2的路径最后有没有\\,没有的话就加。然后再跟去掉盘符的f1路径相加,组成最后的目标路径
File newFile=new File(desPath);
if (!newFile.exists()) {
newFile.mkdir();
}
copyDir(newFile,file);
//新建这个目录
}
}
}
}
拷贝目录
最新推荐文章于 2025-11-29 15:51:28 发布
5817

被折叠的 条评论
为什么被折叠?



