Java文件备份类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 用于文件备份的类
 * 
 * 适用于各种类型文件备份,在原文件的路径下,创建备份文件,命名为 原文件名.bak
 */
public class FileUtils {
	public static String BACKUP_SUFFIX =".bak";
	
	/**
	 * 实现文件复制的函数
	 * 
	 * 采用二进制流的形式来实现文件的读写
	 */
	public static void fileCopy(File srcFile, File destFile) throws Exception{
		InputStream src = new BufferedInputStream(new FileInputStream(srcFile));
		OutputStream dest = new BufferedOutputStream(new FileOutputStream(destFile));
		
		byte[] trans = new byte[1024];
		
		int count = -1;
		
		while((count = src.read(trans)) != -1){
			dest.write(trans, 0, count);
		}
		
		dest.flush();
		src.close();
		dest.close();
	}
		
	/**
	 * 备份文件,在原文件目录下创建备份文件,命名为 原文件名.bak
	 * @param templateFile 需要备份的函数
	 * @return true 成功,false 失败
	 */
	public static boolean backupTemplateFile(String templateFile){
		boolean flag = true;
		
		File srcFile = new File(templateFile);
		if(!srcFile.exists()){
			System.out.println("模板文件不存在");
			return false;
		}
		
		//创建备份文件
		File backUpFile = new File(templateFile+BACKUP_SUFFIX);
		try {
			if(backUpFile.createNewFile()){
				//创建备份文件成功,进行文件复制
				fileCopy(srcFile, backUpFile);
			}
		} catch (Exception e) {
			flag = false;
			System.out.println("备份文件失败");
		}
		
		return flag;
	}
}

 

你可能感兴趣的:(java,文件备份)