首页 > 技术文章 > Java文件备份类

-crazysnail 2014-08-19 21:14 原文

 1 import java.io.BufferedInputStream;
 2 import java.io.BufferedOutputStream;
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 
 9 /**
10  * 用于文件备份的类
11  * 
12  * 适用于各种类型文件备份,在原文件的路径下,创建备份文件,命名为 原文件名.bak
13  */
14 public class FileUtils {
15     public static String BACKUP_SUFFIX =".bak";
16     
17     /**
18      * 实现文件复制的函数
19      * 
20      * 采用二进制流的形式来实现文件的读写
21      */
22     public static void fileCopy(File srcFile, File destFile) throws Exception{
23         InputStream src = new BufferedInputStream(new FileInputStream(srcFile));
24         OutputStream dest = new BufferedOutputStream(new FileOutputStream(destFile));
25         
26         byte[] trans = new byte[1024];
27         
28         int count = -1;
29         
30         while((count = src.read(trans)) != -1){
31             dest.write(trans, 0, count);
32         }
33         
34         dest.flush();
35         src.close();
36         dest.close();
37     }
38         
39     /**
40      * 备份文件,在原文件目录下创建备份文件,命名为 原文件名.bak
41      * @param templateFile 需要备份的函数
42      * @return true 成功,false 失败
43      */
44     public static boolean backupTemplateFile(String templateFile){
45         boolean flag = true;
46         
47         File srcFile = new File(templateFile);
48         if(!srcFile.exists()){
49             System.out.println("模板文件不存在");
50             return false;
51         }
52         
53         //创建备份文件
54         File backUpFile = new File(templateFile+BACKUP_SUFFIX);
55         try {
56             if(backUpFile.createNewFile()){
57                 //创建备份文件成功,进行文件复制
58                 fileCopy(srcFile, backUpFile);
59             }
60         } catch (Exception e) {
61             flag = false;
62             System.out.println("备份文件失败");
63         }
64         
65         return flag;
66     }
67 }

 

推荐阅读