自己做過Java對Tomcat的啟動停止通過Runtime.exec()執行對應的startup.bat檔案和shutdown.bat檔案.
代碼等會貼首先配置環境變量JAVA的JDK和JRE這裡就不介紹了,本人使用jdk1.6+Tomcat6,Tomcat7
這裡先配置CATALINA_HOME 為Tomcat的根目錄下面就為bin和webapps目錄 在環境變量中添加CATALINA_HOME 并且在PATH中配置
%CATALINA_HOME %\bin;%CATALINA_HOME %\lib; 這裡需要重新啟動才能讀取到CATALINA_HOME的資訊。
最簡單的測試代碼為:Process p = Runtime.getRuntime().exec("Tomcat startup.bat路徑")
但因為有時候我們需要擷取Tomcat的列印資訊 或者我們執行的bat裡面可能存在阻塞
則我們需要擷取Process的getInputStream 和getErrorStream
public class Test_Strat_EndTomcat {
public static String path = "F:\\NgxTomcat\\TomcatAll\\Tomcat1\\bin";
public static void main(String args[]) {
Test_Strat_EndTomcat tt = new Test_Strat_EndTomcat();
tt.startTomcat();
}
public void startTomcat() {
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(path + "\\startUp.bat");
ProcessOutputThread p1 = new ProcessOutputThread(p.getInputStream());
ProcessOutputThread p2 = new ProcessOutputThread(p.getErrorStream());
p1.start();
p2.start();
try {
if (p.waitFor() > -1) {
System.out.println("完成bat檔案執行!");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ProcessOutputThread extends Thread {
private InputStream is;
public ProcessOutputThread(InputStream is) throws IOException {
if (null == is) {
throw new IOException("the provided InputStream is null");
}
this.is = is;
}
@Override
public void run() {
InputStreamReader ir = null;
BufferedReader br = null;
try {
ir = new InputStreamReader(this.is);
br = new BufferedReader(ir);
String output = null;
while (null != (output = br.readLine())) {
System.out.println(output);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != br) {
br.close();
}
if (null != ir) {
ir.close();
}
if (null != this.is) {
this.is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}