系统中需要实现在网页上点击按钮从而自动更新网站版本,而更新网站版本需要在服务器上执行一系列的操作,将一系列的命令写入shell脚本中,在java后台中调用并执行该脚本,就可以实现需求功能。
进入正题,在java中调用一个shell脚本,例如调用“/home/tomcat/bin/start.sh”这个脚本,代码如下:
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
public class test{
/**
* 运行shell脚本
* @param shell 需要运行的shell脚本
*/
public static void execShell(String shell){
try {
Runtime rt = Runtime.getRuntime();
rt.exec(shell);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 运行shell
*
* @param shStr
* 需要执行的shell
* @return
* @throws IOException
*/
public static List runShell(String shStr) throws Exception {
List<String> strList = new ArrayList();
Process process;
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
//process = Runtime.getRuntime().exec(shStr);
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
process.waitFor();
while ((line = input.readLine()) != null){
System.out.println(line);
strList.add(line);
}
return strList;
}
public static void main(String []arge)throws Exception {
test t=new test();
t.runShell("/home/ubuntu/soft/tomcat/bin/startup.sh")
}
}
注意:执行的脚本跟java进程在一个进程中。