フォルダバックアップツール


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 + " ");
		}
	}
}