由于项目迁移,一些附件需要条件性的保留,写了下面的一段代码,做个记录,也方便日后自己直接使用;
下面的方法是复制单个文件的,循环调用即可
//未复制成功的文件集合信息,可以在程序完成后输出,确保文件复制完全
static List<String> errList = new ArrayList<>();
/**
* 复制文件
* 两参数的格式为文件全路径信息,如:/opt/img/image.png
* @param copy 复制
* @param past 粘贴
*/
@SuppressWarnings("resource")
public static void copyFile(String copy, String past) {
FileChannel input = null;
FileChannel output = null;
try {
File file = new File(copy);
if (file.exists()) {
input = new FileInputStream(file).getChannel();
File newFile = new File(past);
if (!newFile.getParentFile().exists()) //文件夹不存在时先创建
newFile.getParentFile().mkdirs();
output = new FileOutputStream(newFile).getChannel();
output.transferFrom(input, 0, input.size());
}else{
errList.add(copy);
System.err.println("文件不存在:" + copy);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null != input)
input.close();
if(null != output)
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}