java调用shell

在写程序时,有时需要在java程序中调用shell脚本,可以通过Runtime的exec方法来调用shell程序,运行脚本。

每个Java 应用程序都有一个Runtime 类实例,使应用程序能够与其运行的环境相连接。通过Runtime对象可以返回运行环境的情况,包括CPU数,虚拟机内存大小等,并能够通过exec方法调用执行命令。可以通过getRuntime 方法获取当前Runtime实例。

 

public boolean ExeShell(){  
    Runtime rt = Runtime.getRuntime();  
    try {  
        Process p = rt.exec(checkShellName);  
        if(p.waitFor() != 0)  
            return false;  
    } catch (IOException e) {  
        SysLog.error("没有找到检测脚本");  
        return false;  
    } catch (InterruptedException e) {  
        e.printStackTrace();  
        return false;  
    }  
    return true; 
}

其中p.waitFor()语句用来等待子进程结束,其返回值为进程结束退出码。

posted on 2010-07-22 16:56  谷底望月  阅读(587)  评论(0编辑  收藏  举报

导航