不知道java如何调用shell脚本?进来教你10行代码搞定

产品与开发的战争

       前段时间,产品提了个挺离谱的需求:经过java服务启动本身所须要的数据库和redis。什么意思呢,意思就是咱们须要提供一个java服务,可是呢,咱们这个java服务用到的mysql和redis没有现成的,须要由这个java服务去安装部署mysql和redis,而后再提供给本身用。
       emmmm…当时我人就傻了,后面我一想,产品都敢想这个需求,难到我堂堂一个技术还不敢去实现吗?java

收起咱们40米大砍刀,直接上干货:mysql

java调用shell脚本

public static String doExec(String instruction) {
    logger.log(Level.INFO, "===execute instruction :" + instruction);
    StringBuffer result = new StringBuffer();
    Process process = null;
    BufferedReader bufrIn = null;
    BufferedReader bufrError = null;
    try {
        Runtime run = Runtime.getRuntime();
        process = run.exec(instruction);

        // 方法阻塞, 等待命令执行完成(成功会返回0)
        process.waitFor();

        bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
        bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
        // 读取输出
        String line;
        while ((line = bufrIn.readLine()) != null) {
            result.append(line).append('\n');
        }
        while ((line = bufrError.readLine()) != null) {
            result.append(line).append('\n');
        }
        logger.log(Level.INFO, "===execute instruction success :" + instruction+" , result is :"+result);
    } catch (Exception e) {
        logger.log(Level.WARNING, "===execute instruction error :" + e);
    } finally {
        MyFileUtils.closeStream(bufrIn);
        MyFileUtils.closeStream(bufrError);
        // 销毁子进程
        if (process != null) {
            process.destroy();
        }
    }
    return result.toString();
}

固然,这个方法不仅仅局限于安装部署mysql和redis,支持任意sh命令,感兴趣的朋友能够拿去试试了!git

>>>源码下载连接>>>redis

相关文章
相关标签/搜索