在者就是java中怎样调用shell脚本 及怎样给shell传参
网上找到好几种写法(实质都是Runtime.getRuntime().exec();方法不同重载形式):' v- a9 g, r/ @. a' }
* O2 Y! h+ J: a$ Y
第一>>>>:String[] cmd = new String[length];
cmd[0] = "./shllName.sh";
for(int i =0; i < list.size(); i ++){ 2 Y0 m- Z1 A( s* \2 ^5 y& [" n+ v
/ w+ m: H+ T9 ?) B" W7 X" Z
cmd[i] = list.get(i); //对字符串数组赋值(这就是给shell脚本传的参数) " c# z S: j! x/ l; }# G) Z& T M
: S+ G8 R+ ]9 V( Q1 h5 H0 p7 a
}
第二>>>:Sring[] cmd = {"/bin/sh/", "-c", "parma1", "param2"....};
第三>>>: 把调用shell及参数直接写在放在中即 Process pcs = Runtime.getRuntime().exec("sh shellName.sh 'param1' 'param2'...");. y- }1 W! x* ?0 `1 w
例子1:
Process pcs = Runtime.getRuntime().exec(cmd); % q( H" B5 K4 X6 k6 b+ L! |
V8 D+ T' p8 T! w, R1 }
//若不加这下面的代码也调不成功shell脚本
InputStreamReader ir = new InputStreamReader(pcs.getInputStream()); $ H9 O3 Z- |* G- S! W4 X2 _
LineNumberReader input = new LineNumberReader(ir); 9 v$ u& M' Y: v% f9 D
String line = null;
while ((line = input.readLine()) != null){
System.out.println(line); & V0 D% z* t E+ F/ l9 f8 W- H
}
if(null != input){
input.close();
}
if(null != ir){
ir.close();
} 1 A% b4 T" b3 v( }
int extValue = pcs.waitFor(); //返回码 0 表示正常退出 1表示异常退出
例子2, javascript 调用shell
String script = "cat /opt/local/apache-tomcat-6.0.26/webapps/deploy/data/show.txt";
StringBuffer outStr = new StringBuffer();
Process p = Runtime.getRuntime().exec(script);
InputStream processIn = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(processIn));
String input = null;
while( (input=br.readLine()) != null ) {
out.println(input);