在用java开发时,有时候会遇到需要调用系统命令或者外部脚本,当前文章给出调用方法。代码如下:
/**
* 转换脚本路径为在win、linux中可执行的命令
*
* @param scriptPath
* 脚本路径
* @return 在linux或window中可执行的命令
*/
public static String[] convertExecuteCommand(String scriptPath) {
String[] cmdArray = null;
if (SystemUtil.isWindows()) {
LinkedList<String> cmdList = new LinkedList<String>();
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 =