将文件夹下的内容复制到指定路径下(保持原结构)
/**
* 将文件夹下的内容复制到指定路径下(保持原结构)
* @param sourcePath
* @param targetPath
*/
public static void copyDir(String sourcePath,String targetPath) {
File file = new File(sourcePath);
//标记1(两处作用相同)
File targetFile = new File(targetPath);//递归循环走此处一定是文件夹,所以创建为下一级文件夹
if (!targetFile.exists()) {
targetFile.mkdirs();
}
if (file.isDirectory()){
File[] listFiles = file.listFiles();
for (File listFile : listFiles) {
String targetPathNew = targetPath + File.separator+ listFile.getName();
if (listFile.isDirectory()){
copyDir(listFile.getPath(),targetPathNew);
}else{
copyFile(listFile.getPath(), targetPathNew);
}
}
}else{
copyFile(sourcePath, targetPath);
}
}
将文件复制到指定路径下
/**
* 将文件复制到指定路径下
* @param sourcePath
* @param targetPath
*/
public static void copyFile(String sourcePath, String targetPath) {
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(targetFile);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}