import java.io.*;
public class Test2 {
public static void main(String[] args) throws IOException {
File in = new File("D:\\test\\");
File out = new File("D:\\abc\\");
copyDirectory(in, out);
}
//复制目录
public static void copyDirectory(File in, File out){
//判断目标目录是否存在
if (!out.exists()) {
//目标目录不存在,创建此目录
out.mkdir();
}
//获取目标目录绝对路径
String path = out.getPath();
//获取源目录下的所有目录、文件,并遍历
File[] inFiles = in.listFiles();
for (File file : inFiles) {
//更改目标路径
out = new File(path, file.getName());
//判断file是否为目录,
//如果是目录则复制此目录,如果不是则复制此文件
if (file.isDirectory()) {
copyDirectory(file, out);
} else {
copyFile(file, out);
}
}
}
//复制文件
public static void copyFile(File in, File out) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//创建输入输出流
fis = new FileInputStream(in);
fos = new FileOutputStream(out);
//复制文件————读取源文件数据,写入到目标文件
byte[] data = new byte[1024];
int len;
while ((len = fis.read(data)) != -1) {
fos.write(data, 0, len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//关闭流
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}