java中备份mysql数据库的通用方法,支持win和linux
备份:
public static void backup() {
try {
Runtime rt = Runtime.getRuntime();
Process child = rt.exec("mysqldump -u用户名 -p密码 -R -c --set-charset=utf8 数据库名");
InputStream in = child.getInputStream();
InputStreamReader xx = new InputStreamReader(in, "utf8");
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(xx);
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
FileOutputStream fout = new FileOutputStream("备份的文件路径名");
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
writer.write(outStr);
writer.flush();
in.close();
xx.close();
br.close();
writer.close();
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
还原:
public static void load() {
try {
String fPath = "备份的文件路径名";
Runtime rt = Runtime.getRuntime();
Process child = rt.exec("mysql -u用户名 -p密码 数据库名");
OutputStream out = child.getOutputStream();
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
writer.flush();
out.close();
br.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}