您的位置:首页 > 运维架构 > Shell

Java执行shell脚本文件

2014-08-26 16:36 302 查看
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,搞定收工!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 执行脚本 shell