Java文件備份類


 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM