JAVA启动停止Tomcat服务

自己做过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();
}
}
}
}

}

    原文作者:lilicshop
    原文地址: https://blog.csdn.net/lilicshop/article/details/52097511
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞