java调用shell脚本

hello_world.txt文件内容
    hello world !!!
hello_world.sh脚本
    #!/bin/bash
    cat /opt/hello_world.txt
java代码
    public static void main(String[] args) throws Exception {
        String shell_path="/opt/hello_world.sh";
        Process ps = Runtime.getRuntime().exec(shell_path);
        ps.waitFor();//如果没有返回值到这里就可以结束了

        BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        System.out.println(sb.toString());
    }
注意:在调用时需要Process执行waitFor()函数,因为shell进程是JAVA进程的子进程,JAVA作为父进程需要等待子进程执行完毕。
在eclipse控制台输出时并不是边执行边输出,而是shell全部执行完毕后输出。如果执行较为复杂的shell脚本看到没有输出时可能会误以为没有执行,这个时候看看终端里面的进程,TOP命令一下就能看到其实shell脚本已经开始执行了。


转载于:https://www.cnblogs.com/timeTraveler/p/10760176.html

你可能感兴趣的:(java调用shell脚本)