【项目总结:波士顿东大校友会】在线文件备份,数据库备份工具类

一、MySQL备份实现工具类

package org.konghao.basic.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MySQLUtil {
	private static MySQLUtil util = null;
	/**
	 * 要备份的文件名
	 */
	private String filename;
	/**
	 * 需要备份到哪个文件夹中
	 */
	private String backupDir;
	/**
	 * 需要备份的几个基本信息
	 */
	private String database;
	private String username;
	private String password;
	
	
	private MySQLUtil(){}
	
	public static MySQLUtil getInstance() {
		if(util==null) util = new MySQLUtil();
		return util;
	}
	
	public void setCfg(String filename,String backupDir,String database,String username,String password) {
		this.filename = filename;
		this.backupDir = backupDir;
		this.database = database;
		this.username = username;
		this.password = password;
	}
	
	public void backup() {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			String cmd = "cmd /c mysqldump -u"+username+" -p"+password+" "+database;//备份指令
			Process proc = Runtime.getRuntime().exec(cmd);
			br = new BufferedReader(new InputStreamReader(proc.getInputStream()));//获得执行进程的输入流并转换为缓冲输入流,以便逐行读取
			bw = new BufferedWriter(
					new FileWriter(backupDir+File.separator+filename+".sql"));//准备备份文件的缓冲输出流,将数据输出到指定文件目录中
			System.out.println(backupDir+File.separator+filename);
			String str = null;
			while((str=br.readLine())!=null) {
				bw.write(str);
				bw.newLine();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(br!=null) br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(bw!=null) bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void resume() {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			String cmd = "cmd /c mysql -u"+username+" -p"+password+" "+database;//恢复命令
			Process proc = Runtime.getRuntime().exec(cmd);
			bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
			br = new BufferedReader(new FileReader(backupDir+File.separator+filename+".sql"));
			String str = null;
			while((str=br.readLine())!=null) {
				bw.write(str);
				bw.newLine();
			}
			br.close();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(br!=null) br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(bw!=null) bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


二、备份的逻辑过程工具类
package org.konghao.basic.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.konghao.basic.model.BackupFile;

public class BackupFileUtil {
	private static BackupFileUtil util;
	private String backupFile;
	private static String realPath;//项目的绝对路径
	private String database;
	private String username;
	private String password;
	private List<String> backupFiles;
	private final static String DATABASE_NAME = "database";
	private final static String BACKUP_NAME = "backup";
	
	private BackupFileUtil() throws IOException{
		Properties prop = new Properties();
		prop.load(BackupFileUtil.class.getClassLoader().getResourceAsStream("backup.properties"));
		database = prop.getProperty("database");
		username = prop.getProperty("database_username");
		password = prop.getProperty("database_password");
		backupFile = prop.getProperty("backupFile");
		
		File bf = new File(realPath+File.separator+backupFile);//备份文件存放地址
		if(!bf.exists()) bf.mkdirs();
		backupFiles = new ArrayList<String>();
		//添加要备份或者要恢复的文件夹
		String fs = prop.getProperty("file");//要备份目标文件的地址(自由配置在文件中)
		
		String[] fas = fs.split(",");
		for(String f:fas) {
			backupFiles.add(f);
		}
		
	}
	
	public static BackupFileUtil getInstance(String realPath) {
		try {
			BackupFileUtil.realPath = realPath;
			if(util==null) util = new BackupFileUtil();
			return util;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 列表所有的备份文件
	 * @return
	 */
	public List<BackupFile> listBackups() {
		File [] fs = new File(realPath+File.separator+backupFile).listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				if(pathname.isDirectory())
					return false;
				return true;
			}
		});
		List<BackupFile> bs = new ArrayList<BackupFile>();
		BackupFile bf = null;
		for(File f:fs) {
			bf = new BackupFile();
			bf.setName(f.getName());
			bf.setSize((int)(f.length()/1024));
			bf.setTime(new Date(f.lastModified()));
			bf.setFiletype(f.getName().substring(f.getName().lastIndexOf(".")+1));
			bs.add(bf);
		}
		Collections.sort(bs);
		return bs;
	}
	
	public void backup(String name) {
		String bp = realPath+File.separator+backupFile+File.separator+BACKUP_NAME;
		try {
			//1、创建备份文件夹对象
			File bpf = new File(bp);
			bpf.mkdirs();
			//1、导出数据库
			MySQLUtil msu = MySQLUtil.getInstance();
			msu.setCfg(DATABASE_NAME, bp, database, username, password);
			msu.backup();
			//2、将要备份的文件夹拷贝到目标文件夹中
			for(String f:backupFiles) {
				String src = realPath+File.separator+f;
				String dest = bp+f;
				FileUtils.copyDirectory(new File(src), new File(dest));
			}
			//3、tar和gz
			TarAndGzipUtil tagu = TarAndGzipUtil.getInstance();
			tagu.tarFile(bp,realPath+File.separator+backupFile+File.separator+new Date().getTime()+"_"+name+".tar");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				FileUtils.deleteDirectory(new File(bp));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	//恢复的name就是整个文件的名称
	public void resume(String name) {
		String op = realPath+File.separator+backupFile+File.separator+BACKUP_NAME;
		try {
			//1、将文件进行解压缩
			String fp = realPath+File.separator+backupFile+File.separator+name;
			TarAndGzipUtil tagu = TarAndGzipUtil.getInstance();
			tagu.unTarFile(new File(fp), realPath+File.separator+backupFile);
			//2、拷贝并且覆盖相应的文件夹
			for(String f:backupFiles) {
				//先删除原有的文件夹
				String src = op+f;
				String dest = realPath+File.separator+f;
				File dfd = new File(dest);
				if(!dfd.exists()) dfd.mkdirs();
				FileUtils.deleteDirectory(dfd);
				FileUtils.copyDirectory(new File(src), dfd);
			}
			//3、恢复数据库
			MySQLUtil msu = MySQLUtil.getInstance();
			msu.setCfg(DATABASE_NAME, op, database, username, password);
			msu.resume();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				FileUtils.deleteDirectory(new File(op));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 要删除的文件的名称
	 * @param name
	 */
	public void delete(String name) {
		File f = new File(realPath+File.separator+backupFile+File.separator+name);
		f.delete();
	}
}

三、备份文件类

package org.konghao.basic.model;

import java.util.Date;

public class BackupFile implements Comparable<BackupFile>{
	/**
	 * 备份的文件名称
	 */
	private String name;
	/**
	 * 备份的文件时间
	 */
	private Date time;
	/**
	 * 备份的文件的尺寸
	 */
	private int size;
	/**
	 * 备份的文件类型
	 */
	private String filetype;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time = time;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	public String getFiletype() {
		return filetype;
	}
	public void setFiletype(String filetype) {
		this.filetype = filetype;
	}
	public int compareTo(BackupFile o) {
		return o.getTime().compareTo(this.getTime());
	}
	@Override
	public String toString() {
		return "BackupFile [name=" + name + ", time=" + time + ", size=" + size
				+ ", filetype=" + filetype + "]";
	}
}

四、backup.properties配置文件

database=fz_cms
database_username=fz
database_password=fz123
backupFile=/resources/backup
file=/resources/indexPic,/resources/upload

五、Controller

package org.konghao.cms.controller;

import javax.inject.Inject;

import org.konghao.basic.model.SystemContext;
import org.konghao.basic.util.BackupFileUtil;
import org.konghao.cms.auth.AuthClass;
import org.konghao.cms.service.IIndexService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import freemarker.ext.beans.MapModel;

@AuthClass
@Controller
@RequestMapping("/admin")
public class BackupController {
	private IIndexService indexService;
	
	
	public IIndexService getIndexService() {
		return indexService;
	}
	@Inject
	public void setIndexService(IIndexService indexService) {
		this.indexService = indexService;
	}

	@RequestMapping(value="/backup/add",method=RequestMethod.GET)
	public String backup() {
		return "backup/add";
	}
	
	@RequestMapping(value="/backup/add",method=RequestMethod.POST)
	public String backup(String backupFilename) {
		BackupFileUtil bfu = BackupFileUtil.getInstance(SystemContext.getRealPath());
		bfu.backup(backupFilename);
		return "redirect:/admin/backups";
	}
	
	@RequestMapping(value="/backups")
	public String list(MapModel model) {
		BackupFileUtil bfu = BackupFileUtil.getInstance(SystemContext.getRealPath());
		model.addAttribute("backups",bfu.listBackups());
		return "backup/list";
	}
	
	@RequestMapping("delete/{name}")
	public String delete(@PathVariable String name,String type) {
		BackupFileUtil bfu = BackupFileUtil.getInstance(SystemContext.getRealPath());
		bfu.delete(name+"."+type);
		return "redirect:/admin/backups";
	}
	
	@RequestMapping("resume/{name}")
	public String resume(@PathVariable String name,String type) {
		BackupFileUtil bfu = BackupFileUtil.getInstance(SystemContext.getRealPath());
		bfu.resume(name+"."+type);
		indexService.generateTop();
		indexService.generateBody();
		indexService.generateBottom();
		return "redirect:/admin/backups";
	}
	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值