java代码关闭tomcat程序

1.通过java代码实现tomcat的关闭

2.tomcatStop.java

 1 package test;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 public class tomcatStop {
 8 
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         System.out.println("访问已超出日访问量");
12         String command = "D:\\apache-tomcat-8.5.39\\bin\\shutdown.bat";// 关闭tomcat命令
13         try {
14             callCommand(command);
15         } catch (IOException e) {
16             System.out.println("执行命令时出错:" + e.getMessage());
17         }
18     }
19 
20     public static void callCommand(String command) throws IOException {
21 
22         Runtime runtime = Runtime.getRuntime();// 返回与当前的Java应用相关的运行时对象
23         // 指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例
24         Process process = runtime.exec(command);
25         runtime.gc();// 运行垃圾回收器
26         String line = null;
27         String content = "";
28         BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
29         while ((line = br.readLine()) != null) {
30             content += line + "\r\n";
31         }
32         System.out.println(content);
33 
34     }
35 }
tomcatStop.java

3.执行关闭命令

4.常见错误

执行代码后可能出现:

The CATALINA_HOME environment variable is not defined correctly

This environment variable is needed to run this program
此时需设置环境变量:
本人设置后运行依然报错,但是将电脑注销一下再次运行即可
posted @ 2019-05-24 11:15  拼搏进取吧  阅读(1290)  评论(0编辑  收藏  举报