package cn.sxt.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
- 拷贝文件夹
- @author Hao Chen
*/
public class CopyDir {
public static void main(String[] args) {
copyDir("E:/MyEclipseWorkSpace/IO_study02","D:/MyEclipseWorkSpace/IO_study02");
}
public static void copyDir(String srcPath,String destPath){
//1.创建源
File src=new File(srcPath);
File dest=new File(destPath);
String[] filePath=src.list(); //获取目标文件夹下所有的文件以及文件夹名称
if(!dest.exists()){ //如果目标文件夹不存在,则创建该文件夹
dest.mkdirs();
}
for(String temp:filePath){
//检查数组中的每一个元素是文件还是文件夹
//是文件夹,则递归调用copyDir
if(new File(srcPath+File.separator+temp).isDirectory()){
copyDir(srcPath+File.separator+temp,destPath+File.separator+temp);
}
//是文件,调用copyFile
else{
copyFile(srcPath+File.separator+temp,destPath+File.separator+temp);
}
}
}
public static void copyFile(String srcPath,String destPath){
//1.创建源
File src=new File(srcPath); //源头
File dest=new File(destPath); //目的地
//2.选择流
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream(src);
os=new FileOutputStream(dest,true);
//3.操作(读入与写出)
int len=-1;
byte[] flush=new byte[1024];
while((len=is.read(flush))!=-1){
os.write(flush,0,len); //写到目标文件
os.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//4.释放资源,先使用的后释放
try {
if(os!=null){
os.close();
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}