public static void copyFolder(File sourcePath, String targetPath) throws FileNotFoundException {
if (!sourcePath.exists()) { // 源目录不存在
throw new FileNotFoundException(sourcePath.getAbsolutePath() + "not found");
}
if (!new File(targetPath).exists()) { // 创建目标目录
new File(targetPath).mkdirs();
}
FileInputStream inputStream = null;
FileOutputStream outputString = null;
FileChannel channelIn = null;
FileChannel channelOut = null;
String targetFile = null;
for (File file: sourcePath.listFiles()) {
targetFile = targetPath + File.separator + file.getName();
if (file.isFile()) {
try {
inputStream = new FileInputStream(file);
outputString = new FileOutputStream(targetFile);
channelIn = inputStream.getChannel();
channelOut = outputString.getChannel();
channelIn.transferTo(0, channelIn.size(), channelOut);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
outputString.close();
channelIn.close();
channelOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
copyFolder(file, targetFile);
}
}
}