© 版权声明:本文为博主原创文章,转载请注明出处
通过java代码实现Tomcat的开启与关闭
1.项目结构
2.CallTomcat.java
package com.calltomcat.test;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;public class CallTomcat {public static void main(String[] args) {//String command = "E:\\apache-tomcat-7.0.76\\bin\\startup.bat";//启动tomcat命令//String command = "E:\\apache-tomcat-7.0.76\\bin\\tomcat7w.exe";//启动Tomcat命令,仅限windows版本,无弹框String command = "E:\\apache-tomcat-7.0.76\\bin\\shutdown.bat";//关闭tomcat命令CallTomcat callTomcat = new CallTomcat();try {callTomcat.callCommand(command);} catch (IOException e) {System.out.println("执行命令时出错:" + e.getMessage());}}/*** 执行命令* * @throws IOException*/private void callCommand(String command) throws IOException {Runtime runtime = Runtime.getRuntime();//返回与当前的Java应用相关的运行时对象//指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例Process process = runtime.exec(command);runtime.gc();//运行垃圾回收器String line = null;String content = "";BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));while((line = br.readLine()) != null) {content += line + "\r\n";}System.out.println(content);}}
3.效果预览
3.1 执行开启命令
3.2 执行关闭命令
4.常见错误
执行代码后可能出现:
The CATALINA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
此时需设置环境变量:
本人设置后运行依然报错,但是将电脑注销一下再次运行即可。
5.说明
若是执行startup.bat会自动出现弹框,但是若执行tomcat7w.exe(根据tomcat版本有所不同)则不会出现弹框。--仅windows版本,其他版本无.exe文件。