數據庫文件導出的shell文件:#!/bin/bash
mysqldump -h{host} -u{userName} -p{password} --skip-lock-tables dbName tableName>db-entity.sqlmysql
數據庫文件導入的shell文件:#!/bin/bash
mysql -h{host} -u{userName} -p{password} dbName <db-entity.sqlsql
注:host/userName/password 是Java調用shell時傳遞過來的參數shell
Java代碼:數據庫
HashMap<String,String> rkdMap = new HashMap<String, String>(); //將參數放入集合中
rkdMap.put("host", dbAddress);
rkdMap.put("userName", userName);
rkdMap.put("password", passWord);
String command = JSONUtil.getStringByParamMap(commandPath,rkdMap);bash
rt = ShellUtil.execCmd(command);app
/ * *
* execCmd()方法
* 執行系統命令, 返回執行結果
* @param cmd 須要執行的命令
*/
public static String execCmd(String cmd) {
StringBuilder result = new StringBuilder();ui
Process process = null;
BufferedReader bufrIn = null;
BufferedReader bufrError = null;spa
try {
String[] commond = {"/bin/sh","-c",cmd};
// 1. 執行命令, 返回一個子進程對象(命令在子進程中執行)
process = Runtime.getRuntime().exec(commond);.net
// 2. 方法阻塞, 等待命令執行完成(成功會返回0)
process.waitFor();對象
// 3. 獲取命令執行結果, 有兩個結果: 正常的輸出 和 錯誤的輸出(PS: 子進程的輸出就是主進程的輸入)
bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
// 4. 讀取輸出
String line = null;
while ((line = bufrIn.readLine()) != null) {
result.append(line).append('\n');
}
while ((line = bufrError.readLine()) != null) {
result.append(line).append('\n');
}
}catch (Exception e){
e.printStackTrace();
}finally {
closeStream(bufrIn);
closeStream(bufrError);
// 5.銷燬子進程
if (process != null) {
process.destroy();
}
}
// 6. 返回執行結果 return result.toString(); }