12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package com.zskk.dicom.monitor.utils;
- import com.zskk.dicom.monitor.config.Configs;
- import com.zskk.dicom.monitor.report.ErrReporter;
- import org.apache.commons.io.FileUtils;
- import org.apache.http.util.TextUtils;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- /**
- * 文件移动帮助类
- */
- public class FileRemoveUtils {
- public static boolean remove(String sourceFilePath, String targetFilePath) {
- if(TextUtils.isEmpty(sourceFilePath) || TextUtils.isEmpty(targetFilePath)) {
- Configs.sysLog.warn("remove error: sourceFilePath or targetFilePath is empty \tsourceFilePath: " + sourceFilePath + "\ttargetFilePath: " + targetFilePath);
- return false;
- }
- File sourceFile = new File(sourceFilePath);
- if(!sourceFile.exists() || !sourceFile.isFile()) {
- Configs.sysLog.warn("remove error: sourceFile not exists or not isFile \tsourceFilePath: " + sourceFilePath);
- return false;
- }
- Configs.sysLog.info("remove file \tsourceFilePath:" + sourceFilePath + "\ttargetFilePath:" + targetFilePath);
- File targetFile = new File(targetFilePath);
- return remove(sourceFile, targetFile);
- }
- private static boolean remove(File sourceFile, File targetFile) {
- String targetFileStr = targetFile.getAbsolutePath();
- if (targetFile.exists()) {
- // 如果移动的文件,已经在目标地址存在 那么,比对Hash值,看是否为同一个文件 如果是同一个文件,只需要删除当前文件,不必移除 如果不是同一个文件,另备份目录
- Configs.sysLog.info("备份目标文件已经存在,需要比对文件Hash值");
- String tHash = FileHashUtil.getFileMD5(targetFile);
- String sHash = FileHashUtil.getFileMD5(sourceFile);
- Configs.sysLog.info(sourceFile.getAbsolutePath() + "[" + sHash + "] ----->>----- " + targetFile.getAbsolutePath() + "[" + tHash + "]");
- if (tHash.equals(sHash)) {
- // 2个文件的Hash值相同 不再移动文件,删除原文件
- boolean isSucDel = sourceFile.delete();
- Configs.sysLog.info("删除源文件:" + sourceFile.getAbsolutePath() + " 结果:" + isSucDel);
- if (!isSucDel) {
- // 文件没有成功删除
- ErrReporter.report("文件删除失败:" + sourceFile.getAbsolutePath());
- }
- return isSucDel;
- } else {
- // 2个文件的Hash值不同
- targetFile = new File(targetFileStr + "2");
- if (targetFile.exists()) {
- // 如果备份文件也存在, 先删除,再将源文件移至此文件
- targetFile.delete();
- }
- }
- }
- boolean flag = false;
- try {
- FileUtils.moveFile(sourceFile, targetFile);
- flag = true;
- Configs.sysLog.info("文件移动-----------:" + sourceFile.getCanonicalPath() + " to:" + targetFile.getAbsolutePath() + " 成功");
- } catch (IOException ioe) {
- if (ioe instanceof FileNotFoundException) {
- // 源文件已不存在
- Configs.sysLog.info("文件移动------------:" + sourceFile.getAbsolutePath() + " to:" + targetFile.getAbsolutePath() + " " + ioe.getMessage());
- } else {
- // 文件没有成功删除
- ErrReporter.report("文件移动失败----------:" + sourceFile.getAbsolutePath() + " to:" + targetFileStr + " " + ioe.getMessage());
- }
- }
- return flag;
- }
- }
|