package com.gary.file;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
* 文件夹备份
* @author gary
*
*/
public class FileSync {
//要备份的目录
static final String targetDir = "F:\\myTemp\\test\\target";
//备份到
static final String bakDir = "F:\\myTemp\\test\\bakdir";
public static void main(String[] args) {
File targetDirFile = new File(targetDir);
File bakDirFile = new File(bakDir);
if(!targetDirFile.exists()){
System.out.println("目标目录不存在");
System.exit(0);
}
if(!bakDirFile.exists()){
try {
System.out.println("备份目录不存在,创建目录" + bakDirFile.getCanonicalPath());
bakDirFile.mkdirs();
} catch (IOException e) {
System.out.println("创建目录失败");
System.exit(0);
}
}
try {
syncDirectory(new File(targetDir), new File(bakDir));
delMore(new File(targetDir), new File(bakDir));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 同步目录
* @param target
* @param bak
* @throws IOException
*/
private static void syncDirectory(File target, File bak) throws IOException{
if(!bak.exists()){
bak.mkdirs();
if(target.isHidden()){
setHidenAttr(bak);
}
}
String bakDirStr = bak.getCanonicalPath();
File[] targetFiles = target.listFiles();
for (int i = 0; i < targetFiles.length; i++) {
if(targetFiles[i].isDirectory()){
syncDirectory(targetFiles[i], new File(bakDirStr + File.separator + targetFiles[i].getName()));
}else{
File bakFile = new File(bakDirStr + File.separator + targetFiles[i].getName());
if(!bakFile.exists() || targetFiles[i].length() != bakFile.length() || targetFiles[i].lastModified() > bakFile.lastModified()){
FileUtils.copyFile(targetFiles[i], bakFile);
if(targetFiles[i].isHidden()){
setHidenAttr(bakFile);
}
System.out.println("同步文件" + targetFiles[i].getCanonicalPath() + " 到 " + bakFile.getCanonicalPath());
}
}
}
}
/**
* 删除多余文件
* @param target
* @param bak
* @throws IOException
*/
private static void delMore(File target, File bak) throws IOException{
if(!target.exists()){
System.out.println("删除目录" + bak.getCanonicalPath());
FileUtils.deleteDirectory(bak);
}else{
String targetDirStr = target.getCanonicalPath();
File[] bakFiles = bak.listFiles();
for (int i = 0; i < bakFiles.length; i++) {
if(bakFiles[i].isDirectory()){
delMore(new File(targetDirStr + File.separator + bakFiles[i].getName()), bakFiles[i]);
}else{
File targetFile = new File(targetDirStr + File.separator + bakFiles[i].getName());
if(!targetFile.exists()){
System.out.println("删除文件" + bakFiles[i].getCanonicalPath());
bakFiles[i].delete();
}
}
}
}
}
/**
* 为文件添加 隐藏 属性
* @param file
*/
public static void setHidenAttr(File file){
String command = "attrib +H \"" + file.getAbsolutePath() + "\"";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
System.out.println(command + "失败");
}
}
}