Java调用shell脚本

public class ShellTest {private String callScript( String... workspace) { try { File dir = null; if (workspace[0] != null) { dir = new File(workspace[0]); System.out.println(workspace[0]); } // String[] evnp = {"val=2", "call=Bash Shell"}; Process process = Runtime.getRuntime().exec("./invokeJ.sh", null, dir); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = input.readLine()) != null) { result.append(line); result.append("\n"); } input.close(); return result.toString(); } catch (Exception e) { e.printStackTrace(); return "invoke error!"; } }public static void main(String[] args) { // TODO Auto-generated method stub ShellTest call = new ShellTest(); System.err.println(call.callScript("/export/data/shell")); }}

shell脚本的路径和内容如下:
Java调用shell脚本
文章图片

执行结果:
Java调用shell脚本
文章图片

下面是我在服务中封装的方法
private void invokeCommand(final HttpExchange httpExchange) { logger.info("invoke command service start!"); String requestBody = IOUtil.readStream(httpExchange.getRequestBody()); CommandDefinition command = JSON.parseObject(requestBody, CommandDefinition.class); Assert.checkNonNull(command); Assert.check(StringUtils.isBlank(command.getCommand()), "command is null"); Assert.check(StringUtils.isBlank(command.getDir()), "dir is null"); logger.info("invoke command request body:{}", JSONObject.toJSONString(command)); String result = executeCommand(command); logger.info("invoke command result:{}", result); }private String executeCommand(CommandDefinition command) { try { File dirTmp = new File(command.getDir()); Process process = Runtime.getRuntime().exec(command.getDir(), command.getEnvp(), dirTmp); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = input.readLine()) != null) { result.append(line); result.append("\n"); } input.close(); return result.toString(); } catch (Exception e) { e.printStackTrace(); return "invoke error!"; } }

【Java调用shell脚本】Java调用shell脚本
文章图片

如果需要的话只需要关注executeCommand这个方法就可以了

    推荐阅读