public class CopyDirDemo {
public static void main(String[] args) {
String src = "E://2";
String dst = "D://2bak";
copyDir(src, dst);
}
/**
*
* @param src 源文件夹路径
* @param dst 目标文件夹的路径
*/
public static void copyDir(String src,String dst){
//拿到指定文件夹下的所有文件,逐个进行备份
File srcFile = new File(src);//E:/2/
File dstFile = new File(dst);//D:/2dak/
if(!srcFile.exists()){
System.out.println("源文件夹不存在,请检查");
throw new DirNotFoundException("源文件夹不存在");
}
if(!dstFile.exists()){
dstFile.mkdir();
}
File[] listFile = srcFile.listFiles();
for(File f:listFile){
if(f.isFile()){//E:/2/5.txt
copyFile(f,new File(dstFile,f.getName()));//D:/2bak/5.txt
}
if(f.isDirectory()){
copyDir(f.getAbsolutePath(),
new File(dstFile,f.getName()).getAbsolutePath() );
}
}
}
public static void copyFile(File src,File dst){
byte[] b = new byte[1024];
try {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
int count;
while((count=in.read(b))!=-1){
out.write(b, 0, count);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("备份"+src.getAbsolutePath()+"失败");
}
}
}
|
|