Java實現定時備份文件

本文實例為大傢分享瞭Java如何定時備份文件的具體實現代碼,供大傢參考,具體內容如下

程序思路:

1.空目錄不備份,但非空目錄都備份

2.源目錄 source 要遞歸他下面所有的文件和目錄 存入List

3.循環這個list,創建每個文件的目錄

4.開始復制

以下代碼實現瞭定時備份路徑為e:\\a的文件,每30秒進行一次備份,時間可修改。

public class Test12 {

    public static void main(String[] args) throws InterruptedException {

        Timer t = new Timer();
        t.scheduleAtFixedRate(new MyTask(),new Date(),1000*30);

        for(int i = 0;i<10000;i++){
            Thread.sleep(1000);
            System.out.println("warning");
        }


    }

}

class MyTask extends TimerTask{

    static final String SOURCE = "e:\\a";
    static String DEST;

    @Override
    public void run() {

        Date d = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        DEST = "e:\\dest_" + df.format(d);
        File file = new File(SOURCE);
        File dest = new File(DEST);

        if(dest.exists()){
            deleteAll(dest);
        }
        System.out.println("創建備份目錄?"+dest.mkdirs());
        List<File> list = new ArrayList<File>();

        getAllFile(file,list);

        backUp(list,dest);
    }

    //備份
    private static void backUp(List<File> list, File dest) {

        if (list == null || list.size() <= 0) {
            return;
        }
        for (File f : list) {
            String fpath = f.getAbsolutePath();     //取出絕對路徑        e:\\a
            String newpath = fpath.replace(SOURCE, DEST);
            System.out.println("對應的新路徑" + newpath);
            File newFile = new File(newpath);
            if (newFile.getParentFile().exists() == false) {
                System.out.println("創建" + newFile + "的父目錄成功?" + newFile.getParentFile().mkdirs());
            }
            if (f.isFile()) {
                copy(f, newFile);
            }
        }

    }

    //復制
    private static void copy(File inFile, File outFile) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        boolean isFlag = false;

        try {
            fis = new FileInputStream(inFile);
            fos = new FileOutputStream(outFile);

            byte[] bs = new byte[1024];
            int length = -1;
            while ((length = fis.read(bs)) != -1) {
                fos.write(bs, 0, length);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //遞歸獲取原目錄下所有的文件信息
    private static void getAllFile(File source, List<File> list) {
        if (source.isDirectory()) {
            //查看子目錄 listFile()
            File[] fs = source.listFiles();
            if (fs != null && fs.length > 0) {
                //說明有子目錄或子文件
                for (File ff : fs) {
                    getAllFile(ff, list);
                }
            }

        }
        list.add(source);

    }

    //遞歸刪除
    private static void deleteAll(File f) {
        if (f.isDirectory()) {
            File[] fs = f.listFiles();
            if (fs != null && fs.length > 0) {
                for (File file : fs) {
                    deleteAll(file);
                }
            }
        }
        System.out.println(f + "刪除成功?" + f.delete());
    }

}

再為大傢補充一段:

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.io.PrintStream;
 
public class Backup 
{
 public static void main(String[] args) 
 {
  Runtime runtime = Runtime.getRuntime();
  Calendar calendar = Calendar.getInstance();
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
  String currentTime = dateFormat.format(calendar.getTime());
  Process p = null;
  PrintStream print = null;
  StringBuilder buf = new StringBuilder();
  for(String a : args){
   buf.append(a);
   buf.append(" ");
  }
  String databases = buf.toString();
  
  try{
   p = runtime.exec("cmd /c mysqldump -uroot -p1234 -B "+databases+">"+currentTime+".sql.bak");
  }catch (IOException e){
   if( p != null ){
    p.destroy();
   }
   try{
    print = new PrintStream(currentTime+"_backup_err.log");
    dateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
    currentTime = dateFormat.format(calendar.getTime());
    print.println(currentTime+"  backup failed.");
    e.printStackTrace(print);
    print.flush();
   }catch (IOException e2){
 
   }finally{
    if(print!=null){
     print.close();
    }
   }
  }
 }
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: