/**
* 复制文件夹
* @param sourcePath
* @param targetPath
* @throws IOException
*/
public void copyFolder(String sourcePath,String targetPath) throws IOException {
File sourceFile = new File(sourcePath);
if (!sourceFile.exists()){
System.out.println("源文件地址不合法");
return;
}
File targetFile = new File(targetPath);
if (!targetFile.exists()){
targetFile.mkdirs();
}
File[] files = sourceFile.listFiles();
for (File file : files){
System.out.println(file.getName());
if (file.isDirectory()){
copyFolder(sourcePath+"\\"+file.getName(),targetPath+"\\"+file.getName());
}
if (file.isFile()){
copyDocument(sourcePath+"\\"+file.getName(),targetPath+"\\"+file.getName());
}
}
}
/**
* 复制文件
* @param sourcePath
* @param destPath
* @throws IOException
*/
public static void copyDocument(String sourcePath,String destPath) throws IOException {
// 创建字节缓冲流对象
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
// 复制文件
byte[] buf = new byte[1024];
int len = 0;
while((len = bis.read(buf))!=-1){
bos.write(buf, 0, len);
}
bos.close();
bis.close();
}
/**
* 测试代码
* @throws IOException
*/
@Test
public void copyDir() throws IOException {
String sourcePath = "输入你要复制的文件或文件夹";
String targetPath = "输入你要复制的文件存放路径";
copyFolder(sourcePath,targetPath);
}