java调用shell脚本

需要bash环境下执行,Windows推荐安装Git For Windows(国内下载站),Linux下默认就是bash。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
String systemType = "linux";//区分Linux和Windows
String tifShPath = "F:/test.sh";// shell脚本
String cmd = "";
if (systemType.equalsIgnoreCase("linux")) {
try {
Runtime.getRuntime().exec("chmod 755 -R " + tifShPath);//获取可读可执行权限
} catch (IOException e) {
e.printStackTrace();
}
cmd = tifShPath;
} else {// windows
cmd = "bash " + tifShPath;
}
try {
Process child = Runtime.getRuntime().exec(cmd);
InputStream in = child.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
in.close();
child.waitFor();
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e) {
System.out.println(e);
}

参考

文章目录
  1. 参考
本站总访问量 | 本文总阅读量