java执行shell文件

/**
 * 执行Shell脚本
 * 原文链接:https://blog.csdn.net/zhang_yanchao/java/article/details/80811881
 *
 * @param filePath 脚本文件地址
 * @param param    输入参数
 * @return 返回值
 */
public static String execShell(String filePath, String param) {
    try {
        String result = "";
        String[] command = {filePath, param};
        Process ps;
        if (param == null) {
            //执行无参数的脚本
            ps = Runtime.getRuntime().exec(filePath);
        } else {
            //执行带参数的脚本
            ps = Runtime.getRuntime().exec(command);
        }
        int exitValue = ps.waitFor();
        //当返回值为0时表示执行成功
        if (0 != exitValue) {
            throw new AppException("返回代码=" + exitValue);
        }
        //只能接收脚本echo打印的数据,并且是echo打印的最后一次数据,如果想打印所有数据,可以参考本篇文章的脚本编写
        BufferedInputStream in = new BufferedInputStream(ps.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = br.readLine()) != null) {
            log.info("脚本返回的数据如下: " + line);
            result = line;
        }
        in.close();
        br.close();
        return result;
    } catch (Exception ex) {
        log.info("执行shell脚本失败,错误信息:" + ex);
        throw new AppException("执行shell脚本失败,错误信息:" + ex.getMessage());
    }
}

无权限 Cannot run program error=13 Permission denied
Process.waitFor()的返回值含义

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容