数据备份
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
private final static String hostIP = "ip";
private final static String userName = "username";
private final static String password = "pw";
private final static String databaseName = "databaseName";
public static String dumpSql(String name,String savePath){
String fileName = name+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".sql";
File saveFile = new File(savePath);
if (!saveFile.exists()) {
saveFile.mkdirs();
}
if(!savePath.endsWith(File.separator)){
savePath = savePath + File.separator;
}
String dumpStr = " mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName;
try {
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
cmdExecute(dumpStr,printWriter);
}catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
public static void cmdExecute(String cmd,PrintWriter printWriter){
BufferedReader bufferedReader = null;
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line = bufferedReader.readLine())!= null){
printWriter.println(line);
}
printWriter.flush();
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据还原
private final static String hostIP = "ip";
private final static String userName = "username";
private final static String password = "pw";
private final static String databaseName = "databaseName";
public static void reductionSql(String filepath) throws IOException {
String stmt2 = "mysql -h " + hostIP + " -u " + userName + " -p" + password +" " + databaseName;
System.out.println(stmt2);
Runtime rt = Runtime.getRuntime();
Process child =
rt.exec(stmt2);
OutputStream out = child.getOutputStream();
String inStr;
StringBuffer sb = new StringBuffer();
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filepath), "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();
}