码迷,mamicode.com
首页 > 数据库 > 详细

简单的数据库备份与恢复类

时间:2014-11-30 01:01:44      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   http   io   ar   os   sp   文件   on   数据   

/**
 * 数据库备份与恢复类
 * @author Administrator
 */
public class Beifen {
/**
* 数据库备份
* @param cmd 备份命令
* @param filePath 备份文件保存位置
* @return
* @throws IOException
*/
public static boolean sqlDump(String cmd, String filePath)
throws IOException {
boolean falg = false;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
Runtime run = Runtime.getRuntime();
// cmd 命令:
Process p = run.exec(cmd);
is = p.getInputStream();// 控制台的输出信息作为输入流
isr = new InputStreamReader(is, "UTF-8");// 设置输入流编码格式
br = new BufferedReader(isr);
// 将控制台输入信息写入到文件输出流中
fos = new FileOutputStream(filePath);
bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
String temp = null;
while ((temp = br.readLine()) != null) {
bw.write(temp);
bw.newLine();
}


falg = true;
System.out.println("/* Dump  SQL File " + filePath + " OK! */");
} catch (IOException e) {
throw new RuntimeException("请将mysql命令添加到path中!", e);
} finally {
bw.flush();
bw.close();
br.close();
}
return falg;
}


/**
* 恢复数据库
* @param cmd 恢复命令
* @param sqlPath 恢复文件
* @throws IOException
*/
public static void sqlLoad(String cmd, String sqlPath) throws IOException {
OutputStreamWriter writer = null;
OutputStream out = null;
BufferedReader br = null;
try {
Runtime rt = Runtime.getRuntime();
Process child = rt.exec(cmd);
out = child.getOutputStream();// 控制台的输入信息作为输出流
// 输入流
br = new BufferedReader(new InputStreamReader(new FileInputStream(
sqlPath), "utf8"));
// 输出流
writer = new OutputStreamWriter(out, "utf8");
String inStr;
while ((inStr = br.readLine()) != null) {
writer.write(inStr);
writer.write("\r\n");
}
writer.flush();
System.out.println("/* Load  SQL File " + sqlPath + " OK! */");
} catch (Exception e) {
e.printStackTrace();
} finally {
//输入输出流
out.close();
br.close();
writer.close();
}
}
/**
* 测试的main方法
* @param args
*/
public static void main(String[] args) {
//备份数据库
boolean b=false;
try {
 b =
 sqlDump("E:/mysql-5.6.14-winx64/bin/mysqldump -uroot -proot 51sql","c:y_copy04.sql");
 } catch (IOException e){ 
e.printStackTrace();
}
 System.out.println("---------------->"+b);
 //恢复数据库
//  try {
// sqlLoad("E:/mysql-5.6.14-winx64/bin/mysql.exe -uroot -proot  51sql"
//  ,"c:y_copy04.sql");
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}

简单的数据库备份与恢复类

标签:style   http   io   ar   os   sp   文件   on   数据   

原文地址:http://my.oschina.net/nly/blog/350403

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!