本文通过Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件,代码如下:
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.*.dmp.bean.AgentConfigInfo;
import com.*.dmp.bean.MapKeys;
import com.*.dmp.bean.RunStatus;
import com.*.dmp.common.SpringUtils;
public class ExportDataServiceDB2 {
AgentConfigInfo agentConfigInfo = SpringUtils.getContext().getBean(AgentConfigInfo.class);
private Logger LOG = LoggerFactory.getLogger(ExportDataServiceDB2.class);
private StringBuffer resultMsg = new StringBuffer();
String isOK = "0";
private String exportShell = agentConfigInfo.getEXPORT_SHELL();
// private String exportCMD = agentConfigInfo.getEXPORT_CMD();
private StringBuffer exportFilePath = agentConfigInfo.getEXPORT_FILE_PATH();
/**
* @Title: ExportData
* @Description: 调用Shell脚本实现db2数据的导出
* @param dataMap
* @throws IOException 对方法的参数进行描述
* @return HashMap 返回类型
*/
public HashMap ExportData(HashMap dataMap) throws IOException {
String dbSchema = dataMap.get("db_schema");
String dbUser = dataMap.get("db_user");
String dbPassword = dataMap.get("db_password");
String tableName = dataMap.get("table_name");
String interFile = dataMap.get("inter_file");
String delimiter = dataMap.get("delimiter");
String exportLimit = dataMap.get("export_limit");
String filePath = mkDirectory(exportFilePath, interFile);
dataMap.put("file_abs_path", filePath);
String cmdPara = createExportShellParams(dbSchema, dbUser,
dbPassword, tableName, filePath, delimiter, exportLimit);
LOG.info("Export Parameters: " + cmdPara);
resultMsg.append("Export Parameters: " + cmdPara + "\n");
String cmd = exportShell + " " + cmdPara;
Process ps = null;
InputStreamReader isr = null;
LineNumberReader input = null;
String line = null;
try {
LOG.info("Run Command: " + cmd );
resultMsg.append("Run Command: " + cmd + "\n");
ps = Runtime.getRuntime().exec(cmd);
isr = new InputStreamReader(ps.getInputStream()); // 使用Reader进行输入读取和打印
input = new LineNumberReader(isr);
while (null != (line = input.readLine())) {
LOG.info(line);
resultMsg.append(line);
if (line.contains("failed") || line.contains("Failed") || line.contains("FAILED") || line.contains("错误")) {
isOK = RunStatus.EXPORT_FAIL;
dataMap.put("export_status", isOK);
dataMap.put("proc_log", resultMsg.toString());
// dataMap = packageResult(isOK, resultMsg.toString()); // 组装返回的消息
return dataMap;
} else {
isOK = RunStatus.PROC_RUN_SUCCESS;
}
}
// if (0 != ps.waitFor()) {
// isOK = RunStatus.EXPORT_FAIL;
// } else {
// isOK = RunStatus.PROC_RUN_SUCCESS;
// }
} catch (IOException e) {
LOG.error("Run the Command Exception: " + cmd + ": " + e.getMessage());
resultMsg.append("Run the Command Exception: " + cmd + ": " + e.getMessage() + "\n");
isOK = RunStatus.EXPORT_FAIL;
} finally {
if (null != input) {
input.close();
}
if (null != isr) {
isr.close(