Java调用shell脚本

来源:互联网 发布:国外大数据发展现状 编辑:程序博客网 时间:2024/06/11 21:08

刚接触 linux下的开发,最近遇到java调用shell脚本的问题,找到一个比较适合菜鸟级的方法,转述如下:

 

在需要运行的SHELL脚本第一行添加 #!/bin/sh

然后在终端运行  chmod a+x test.sh  就可以把test.sh转化为可执行文件

另外需要注意的是java运行的目录和shell用户可能不同,建议使用全路径,如  /root/bin/test.sh

 

全部代码

------------------------------------------------------------------------------------------------------------------------------

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;


public class RunShell {
   
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("/home/tina/Desktop/cal_time.sh");
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line;
            while((line = input.readLine()) != null)
                System.out.println(line);
            input.close();
            ir.close();
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
-----------------------------------------------------------------------------------------------------------------------------

 

即可正确执行脚本,代码已运行,验证无误