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
發佈了111 篇原創文章 · 獲贊 99 · 訪問量 54萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章