Java调用shell脚本的问题,曾在之前的开发中遇到过,虽然调用方法很简单(貌似当时花了我蛮长时间),还是做个记录吧(年纪大了,易忘哈)~
配置文件中配置shell脚本文件执行命令,如:
sg_sam_command_model=sh ./sam_model.sh
java中获取配置项:
public boolean model(){
try {
String command = SGConfig.getInstance().getItem("sg_sam_command_model");
ScriptUtil.executeScript(command);
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
java执行脚本:
public static void executeScript(String command){
Process pcs = null ;
InputStreamReader is = null;
LineNumberReader in = null;
try{
Runtime rt = Runtime.getRuntime();
pcs = rt.exec(command);
is = new InputStreamReader(pcs.getInputStream());
in = new LineNumberReader(is);
String line;
pcs.waitFor();
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch(InterruptedException e){
System.err.println("processes was interrupted");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(pcs != null){
pcs.destroy();
}
}
}
ok,搞定收工!