java复制文件及文件夹
文件复制
public static void copyByStream(String sourcePath, String targetPath) {
if(StringUtils.isBlank(sourcePath) || StringUtils.isBlank(targetPath)){
log.info("复制文件时文件路径为空");
return;
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(sourcePath);
fos = new FileOutputStream(targetPath);
int len = 0;
byte[] b = new byte[1024];
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
} catch (Exception e) {
log.error("出现异常, detail: ", e);
throw new BaseException(ResponseCode.ERROR.getCode(), "复制文件异常");
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
log.error("关闭输出流出错", e);
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error("关闭输入流出错", e);
}
}
}
}
文件夹级联复制
public static void copyFolder(String sourceFolderPath, String targetFolderPath) {
File sourceFolder = new File(sourceFolderPath);
String[] sourceFilePathList = sourceFolder.list();
File targetFolder = new File(targetFolderPath);
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
try {
for (String filePath : sourceFilePathList) {
if (new File(sourceFolderPath + sourceFolder.separator + filePath).isDirectory()) {
copyFolder(sourceFolderPath + sourceFolder.separator + filePath, targetFolderPath + sourceFolder.separator + filePath);
}
if (new File(sourceFolderPath + sourceFolder.separator + filePath).isFile()) {
copyFile(sourceFolderPath + sourceFolder.separator + filePath, targetFolderPath + sourceFolder.separator + filePath);
}
}
} catch (IOException e) {
log.error("复制文件夹信息出错", e);
throw new BaseException(ResponseCode.ERROR.getCode(), "复制图片异常");
}
}
public static void copyFile(String sourceFilePath, String targetFilePath) throws IOException {
File sourceFile = new File(sourceFilePath);
File targetFile = new File(targetFilePath);
FileInputStream inputStream = new FileInputStream(sourceFile);
FileOutputStream outputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[4096];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}