//mysql 完全備份實現類
package com.sky.mysql;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Properties;
public class MySqlBackup {
public void backup() throws IOException {
Properties pros = new BackupUtil().getPprVue("pro.properties");// 讀取db文件
String username = pros.getProperty("username");//用戶名
String password = pros.getProperty("password");//密碼
String dataName=pros.getProperty("dataName");//數據庫
String address = pros.getProperty("address");//ip地址
//C:\Program Files\MySQL\MySQL Server 5.0\bin
String mysqldump="C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqldump";//mysql安裝目錄
String savePath = pros.getProperty("savePath");//保存的路徑
StringBuffer sb = new StringBuffer();
sb.append(mysqldump);
sb.append(" -u ");
sb.append(username);
sb.append(" ");
sb.append("-p");
sb.append(password+" ");
sb.append(dataName);
sb.append(" ");
sb.append("-h ");
sb.append(address);
System.out.println("\n\t<-------------數據庫備份開始------------->");
try {
Runtime rt = Runtime.getRuntime();
Process process = rt.exec(sb.toString());// 執行命令
InputStream in = process.getInputStream();// 控制檯的輸出信息作爲輸入流
InputStreamReader inputRead = new InputStreamReader(in, "utf8");// 設置輸出流編碼爲utf8
File backupath = new File(savePath);
if (!backupath.exists()) {
backupath.mkdir();
}
String sqlname=new BackupUtil().getTime();//文件名
String filePath = savePath+File.separator + sqlname;//文件路徑
OutputStream outputStream = new FileOutputStream(filePath);
byte[] buff = new byte[512];
int len;
while ((len = in.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
in.close();
inputRead.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\n\t<-------------數據庫備份結束-------------->");
}
public static void main(String[] args) throws IOException {
new MySqlBackup().backup();//數據庫備份
}
}
//mysql 完全備份工具類
package com.sky.mysql;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class BackupUtil {
public Properties getPprVue(String string) {
// BackmysqlUtil.class.getClassLoader().getResourceAsStream(string);
InputStream input=BackupUtil.class.getClassLoader().getResourceAsStream(string);
Properties pro=new Properties();
try {
pro.load(input);
} catch (IOException e) {
e.printStackTrace();
}
return pro;
}
public String getTime(){
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hhmmss");
String s =sdf.format(d);
return s;
}
}
//mysql 完全備份properties文件
username=root
password=1
address=127.0.0.1
savePath=e:\\backup
dataName=pkb