java程序执行linux命令

因某些情况下需要调用Java程序执行Linux命令,过程中有写坑,记录下:

@Slf4j
public class CommandUtil {
    public static Result<Boolean> run(List<String> commandArr){
        File wd = new File("/bin");
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
        } catch (IOException e) {
            log.error("CommandUtil.run IOException",e);
            return CommonError.SERVICE_ERROR.toResult(e.getLocalizedMessage());
        }

        if (proc != null) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true)) {
                for (String command : commandArr) {
                    out.println(command);
                }
                out.println("echo ready exit");
                out.println("exit");

                String result;
                while ((result = in.readLine()) != null) {
                    log.info("command exec result:{}", result);
                }
            } catch (Exception e) {
                log.error("CommandUtil.run Exception", e);
                return CommonError.SERVICE_ERROR.toResult(e.getLocalizedMessage());
            } finally {
                proc.destroy();
            }
            return Result.successResult(true);
        }else {
            return CommonError.SERVICE_ERROR.toResult("Process is null");
        }
    }
}

工具类调用示例:

List<String> commandArr = new ArrayList();
        commandArr.add("cd " + projectRootPath);
        commandArr.add("pwd");
        commandArr.add("cd target/classes");
        commandArr.add("pwd");
        commandArr.add("jar -cvf " + jarOutPathName + " " + jarClassPathName);
        commandArr.add("echo jar update");
        commandArr.add("jar -uvf " + jarOutPathName + " " + jarClassPathName);
        log.info(JSON.toJSONString(commandArr));
        return CommandUtil.run(commandArr);

踩过的坑如下:
上述工具类是打开一个命令行窗口,可执行linux命令cd,用其它方式调用执行cd命令,会出错,异常如下:

java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值