https://www.cnblogs.com/jinjiyese153/p/6744021.html
<https://www.cnblogs.com/jinjiyese153/p/6744021.html>
* 管理 <https://i.cnblogs.com/>
*
Java开启/关闭tomcat服务器 <https://www.cnblogs.com/jinjiyese153/p/6744021.html>
© 版权声明:本文为博主原创文章,转载请注明出处
通过java代码实现Tomcat的开启与关闭
1.项目结构
2.CallTomcat.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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.常见错误
执行代码后可能出现:
1
2
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文件。
热门工具 换一换