Java在windows和linux上调用外部程序

在用java开发时,有时候会遇到需要调用系统命令或者外部脚本,当前文章给出调用方法。代码如下:

    /**
     * 转换脚本路径为在win、linux中可执行的命令
     * 
     * @param scriptPath
     *            脚本路径
     * @return 在linux或window中可执行的命令
     */
    public static String[] convertExecuteCommand(String scriptPath) {
        String[] cmdArray = null;
        if (SystemUtil.isWindows()) {
            LinkedList cmdList = new LinkedList();
            cmdList.addFirst(cmdFormat(scriptPath));
            cmdArray = cmdList.toArray(new String[cmdList.size()]);
        }
        if (SystemUtil.isLinux()) {
            String path = scriptPath.substring(0, scriptPath.lastIndexOf(File.separator));
            String cmdV = scriptPath.substring(scriptPath.lastIndexOf(File.separator) + 1, scriptPath.length() - 1);
            String cmdCommand = buildCmdCommand("&&", cmdV, path, new String[] {});
            cmdArray = new String[] { "/bin/sh", "-c", cmdCommand };
        }
        logger.debug(HikLog.toLog(HikLog.message("parameter convert execute command is:{}")), Arrays.toString(cmdArray));
        return cmdArray;
    }

    /**
     * 将脚本参数和参数转换为win、linux中可执行的命令
     * 
     * @param scriptPath
     * @param parameterArray
     * @return
     */
    public static String[] convertExecuteCommand(String scriptPath, String[] parameterArray) {
        String[] cmdArray = new String[] {};
        if (SystemUtil.isWindows()) {
            LinkedList cmdList = new LinkedList();
            for (int i = 0; i < parameterArray.length; i++) {
                cmdList.add(parameterArray[i]);
            }
            cmdList.addFirst(cmdFormat(scriptPath));
            cmdArray = cmdList.toArray(new String[cmdList.size()]);
        }
        if (SystemUtil.isLinux()) {
            String path = scriptPath.substring(0, scriptPath.lastIndexOf(File.separator));
            String cmdV = scriptPath.substring(scriptPath.lastIndexOf(File.separator) + 1, scriptPath.length() - 1);
            String[] message = new String[] {};
            for (int i = 0; i < parameterArray.length; i++) {
                message[i] = parameterArray[i];
            }
            String cmdCommand = buildCmdCommand("&&", cmdV, path, message);
            cmdArray = new String[] { "/bin/sh", "-c", cmdCommand };
        }
        return cmdArray;
    }

    /**
     * 从process中获取执行结果
     * 
     * @param cmdArray
     * @param process
     * @return
     */
    public static List getAgentReturnValue(String[] cmdArray, Process process) {
        BufferedReader inputBufferedReader = null;
        LinkedList inputResult = new LinkedList();
        BufferedReader errorBufferedReader = null;
        LinkedList errorResult = new LinkedList();
        try {
            inputBufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
            String inputLine = null;
            while ((inputLine = inputBufferedReader.readLine()) != null) {
                logger.debug(HikLog.toLog(HikLog.message("input result line is:{}")), inputLine);
                inputResult.add(inputLine);
            }

            errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), Charset.forName("GBK")));
            String errorLine = null;
            while ((errorLine = errorBufferedReader.readLine()) != null) {
                logger.debug(HikLog.toLog(HikLog.message("error result line is:{}")), errorLine);
                errorResult.add(errorLine);
            }

            if (CollectionUtils.isEmpty(inputResult) && CollectionUtils.isEmpty(errorResult)) {
                logger.info(HikLog.toLog(HikLog.message("return value is empty and sendmessage is:{}")), Arrays.toString(cmdArray));
                throw new ProgramException(DataManagerErrorCode.AGENT_RETURN_RESULT_NULL, DataManagerErrorCode.AGENT_RETURN_RESULT_NULL);
            }
        } catch (Exception e) {
            if (e instanceof ProgramException) {
                throw (ProgramException) e;
            }

            logger.info(HikLog.toLog(HikLog.message("sendmessage is:{} and from BufferedReader reader and  return value has a exception:{}")),
                    Arrays.toString(cmdArray), e);
            throw new ProgramException(DataManagerErrorCode.GET_TASK_RECORD_ERROR, DataManagerErrorCode.GET_TASK_RECORD_ERROR);
        } finally {
            IOUtils.closeQuietly(inputBufferedReader);
            IOUtils.closeQuietly(errorBufferedReader);
        }
        inputResult.addAll(errorResult);
        return inputResult;
    }

    /**
     * 执行脚本
     * 
     * @param cmdArray
     * @return
     */
    public static Process executeScript(String[] cmdArray) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmdArray);
        } catch (Exception e) {
            logger.info(HikLog.toLog(HikLog.message("execute cmd commond has a exception:{}")), e);
            throw new ProgramException(DataManagerErrorCode.EXECUTE_CMD_COMMOND_ERROR, DataManagerErrorCode.EXECUTE_CMD_COMMOND_ERROR);
        }
        return process;
    }

    /**
     * 执行命令行
     * 
     * @param cmdArray
     * @return
     */
    public static Process executeCommand(String command) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            logger.info(HikLog.toLog(HikLog.message("execute cmd commond has a exception:{}")), e);
            throw new ProgramException(DataManagerErrorCode.EXECUTE_CMD_COMMOND_ERROR, DataManagerErrorCode.EXECUTE_CMD_COMMOND_ERROR);
        }
        return process;
    }

    /**
     * 转译命令行
     * 
     * @param str
     * @return
     */
    public static String cmdFormat(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        dest = dest.replaceAll("\"", "\\\\\"");
        return dest;
    }

    /**
     * 组装cmd命令
     * 
     * @param connector
     *            cmd命令之间连接符,bat文件内用\r\n,直接执行用&&
     * @param cmdV
     *            bat或exe文件名 --start.bat
     * @param path
     *            bat或exe文件所在目录
     * @param parameters
     *            bat参数
     * @return
     */
    public static String buildCmdCommand(String connector, String cmdV, String path, String[] parameters) {
        StringBuilder cmd = new StringBuilder();

        cmd.append("cd \"").append(path).append("\"").append(connector);
        cmd.append("./").append(cmdV);

        if (null != parameters) {
            for (String para : parameters) {
                cmd.append(" " + para);
            }
        }
        return cmd.toString();
    }

你可能感兴趣的:(工具)