文件夹按照原始层级copy
对于文件处理的时候会有按照原始文件夹复制的需求,记录一下自己使用的复制文件夹且保留原始层级的代码
/**
* 拷贝文件夹到文件夹
* 递归获取所有层级
* */
private void copyDirectory(File oldFile,String newFile){
if (oldFile.isDirectory()){
//copy 文件夹
File[] files = oldFile.listFiles();
if (files!=null||files.length != 0){
int fileSize = files.length;
for (int i = 0;i < fileSize; i++){
if (files[i].isDirectory()){
copyDirectory(files[i],newFile);
}else {
try {
copyFileByChannels(files[i], new File(newFile+files[i].getName()));
}catch (Exception e){
log.error(e.getMessage());
log.error("copy file error filePath:"+files[i].getPath());
break;
}
}
}
}
}
}
//copy文件
private void copyFileByChannels(File source, File dest) throws IOException {
try (FileChannel inputChannel = new FileInputStream(source).getChannel(); FileChannel outputChannel = new FileOutputStream(dest).getChannel()) {
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
}
}
浙公网安备 33010602011771号