JAVA call Shell Script

在JAVA中调用`Shell`,源于小米开源SQL优化工具[SOAR](https://github.com/XiaoMi/soar),具体工具使用方法可以直接在[GitHub](https://github.com/XiaoMi/soar)上查看。但是该工具没有界面,于是想通过前端界面发送sql到后台,由后台调用shell脚本来执行。
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
30
31
public void testShell(){
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("/Users/alwynxu/Desktop/jmx-demo/test.sh");
// Process process = runtime.exec("java");
process.waitFor();
InputStream inputStream = process.getInputStream();
InputStream errorStream = process.getErrorStream();

byte[] errBytes = new byte[1024];
byte[] inputBytes = new byte[2014];
int errCount = 0;
int inputCount = 0;
System.out.println("执行错误命令:--------");
while ((errCount = errorStream.read(errBytes)) != -1){
String str = new String(errBytes,0, errCount);
System.out.println(str);
}

System.out.println("执行结果:----------");
while ((inputCount = inputStream.read(inputBytes)) != -1){
String str = new String(inputBytes, 0, inputCount);
System.out.println(str);
}

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
1
2
3
4
5
#!/bin/bash
soar=/Users/alwynxu/go/src/github.com/XiaoMi/soar
echo ${soar}
echo 'select * from tb1' | ${soar}/soar > report.md
cat report.md | ${soar}/soar -report-type md2html > report.html
0%