Java代碼調用Shell指令碼並傳入參數實現DB2資料庫表匯出到檔案

來源:互聯網
上載者:User

標籤:des   blog   http   io   os   使用   java   ar   for   

  本文通過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<String,String> 傳回型別     */    public HashMap<String, String> ExportData(HashMap<String, String> 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();            }             if (null != ps) {                ps.destroy();                ps = null;            }        }                 dataMap.put("export_status", isOK);        dataMap.put("proc_log", resultMsg.toString());//      dataMap = packageResult(isOK, resultMsg.toString()); // 組裝返回的訊息         return dataMap;     }     /**     * @Title: createExportShellParams      * @Description:  組裝參數     * @param msgId     * @param dbSchema     * @param dbUser     * @param dbPassword     * @param tableName     * @param filePath     * @param delimiter     * @param exportLimit     * @return String 傳回型別     * @throws     */    private String createExportShellParams(String dbSchema,             String dbUser, String dbPassword, String tableName,            String filePath, String delimiter, String exportLimit) {         StringBuilder params = new StringBuilder();        params.append(dbSchema + " ").append(dbUser + " ").append(dbPassword + " ")            .append(tableName + " ").append(filePath + " ").append(delimiter + " ").append(exportLimit);         return params.toString();    }     /**     * @Title: mkDirectory      * @Description:  根據配置的路徑和檔案名稱,判斷檔案路徑是否存在,若不存在,則先建立,拼接匯出檔案絕對路徑。     * @param filePath     * @param interFile     * @return 對方法的參數進行描述     * @return String 傳回型別     * @throws     */    private String mkDirectory(StringBuffer filePath, String interFile) {                 File file = new File(filePath.toString());                 if ( file.isDirectory() ) {            if (filePath.toString().endsWith("/")) {                filePath.append(interFile);            } else {                filePath.append("/").append(interFile);            }        } else {            LOG.info("The file path is not exists, need to be created now. ");            file.mkdir();            if (filePath.toString().endsWith("/")) {                filePath.append(interFile);            } else {                filePath.append("/").append(interFile);            }        }        return filePath.toString();    }     /** 返回訊息組裝結果 */    private HashMap<String, String> packageResult(String isOK, String resultMsg) {        HashMap<String, String> hsmap = new HashMap<String, String>();        hsmap.put(MapKeys.PROC_STATUS, isOK);        hsmap.put(MapKeys.PROC_LOG, resultMsg);        return hsmap;    } }

  

  傳入的執行參數放入一個Map(HashMap<String, String> dataMap)中:

/**  EXPORT TEST  */map.put("db_schema", "md");map.put("db_user", "root");map.put("db_password", "root");map.put("table_name", "inter_log");map.put("inter_file", "inter_log_20140915.avl");map.put("delimiter", "|");map.put("export_limit", "");

  

  代碼執行之後,將執行日誌以及執行結果也存入該Map中一起返回:

dataMap.put("export_status", isOK);dataMap.put("proc_log", resultMsg.toString()); return dataMap;

  

  執行結果介面:

 

Java代碼調用Shell指令碼並傳入參數實現DB2資料庫表匯出到檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.