public void copyFiles(File rootFile,File copyFile){
if(copyFile.isFile()){
throw new RuntimeException("不能将一个文件夹复制到一个文件当中");
}
String rootPath=rootFile.getAbsolutePath().substring(rootFile.getAbsolutePath().lastIndexOf('\\'));
String path=copyFile.getAbsolutePath()+rootPath;
copyFile=new File(path);
if(rootFile.isFile()){
try {
FileInputStream fis=new FileInputStream(rootFile);
FileOutputStream fos=new FileOutputStream(copyFile);
byte[] b=new byte[1024];
int code;
code = fis.read(b);
while(code!=-1){
fos.write(b, 0, code);
code=fis.read(b);
}
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}else{
copyFile.mkdir();
File[] files=rootFile.listFiles();
if(files.length!=0){
for(File f:files){
this.copyFiles(f, copyFile);
}
}
}
}
测试用例:
File f1=new File("F:\\测试\\a\\haha.txt");
File f2=new File("E:\\练习");
CopyFile cf=new CopyFile();
cf.copyFiles(f1,f2);