工具类:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileHelpUtils {
/** The Constant LOG. */
private static final Logger LOG = LoggerFactory.getLogger(FileHelpUtils.class);
// 拷贝文件到指定目录
public static boolean backupFile(final File srcFile, String copyPath )
{
if (srcFile == null)
{
LOG.error("backSuccess process, source is null!");
return false;
}
File typeFolder = new File(copyPath);
if (typeFolder.exists())
{
LOG.info(" check folder exists! (" + copyPath + ")");
}else{
LOG.info(" create folder (" + copyPath + ")...");
typeFolder.mkdir();
LOG.info(" create folder (" + copyPath + ") end, check exists:" + typeFolder.exists());
}
//Folder: date
String version = new SimpleDateFormat("yyyyMMdd").format(new Date());
final String strDestDirectory = copyPath + File.separator +version;
final File destFolder = new File(strDestDirectory);
if (destFolder.exists())
{
LOG.info(" check folder exists! (" + strDestDirectory + ") ");
}else{
LOG.info(" create folder (" + strDestDirectory + ")...");
destFolder.mkdir();
LOG.info(" create folder (" + strDestDirectory + ") end, check exists:" + destFolder.exists());
}
//file name
final String fileName = srcFile.getName();
//{destDirectory}/{fileName}
final String destFilePath = strDestDirectory + File.separator + fileName;
// Move file
final File destFile = new File(destFilePath);
if (destFile.exists())
{
LOG.info(" Delete old file : " + destFilePath + "!");
destFile.delete();
}
// NEW strategy to avoid move file failure
return reNameFile(srcFile, destFile);
}
public static boolean reNameFile(File oldname, File newname){
try{
// copy file
org.apache.commons.io.FileUtils.copyFile(oldname, newname);
LOG.info(" [OK] Copy file from " + oldname.getPath() + " ----> " + newname + " !");
// delete file
if(oldname.delete()){
LOG.info(" [OK] Delete source file:" + oldname.getPath() + " !");
}
}catch(IOException ioex){
LOG.error(" [KO] Copy file path: " + oldname.getPath() + ". error:" + ioex.getMessage());
return false;
}
return true;
}
public static void main(String[] args) {
backupFile(new File("E:\\rollout_1608284713998.json.gz"),"E:\\home");
}
}