1. 程式人生 > >java 程式碼控制tomcat關閉

java 程式碼控制tomcat關閉


    public static void main(String[] args) {
        String command = "D:\\awgytools\\apache-tomcat-8.0.44\\bin\\shutdown.bat";//關閉tomcat命令
//        String command = "D:\\awgytools\\apache-tomcat-8.0.44\\bin\\startup.bat";//啟動tomcat命令
//        String command = "D:\\awgytools\\apache-tomcat-8.0.44\\bin\\tomcat7w.exe";
        CallTomcat callTomcat = new CallTomcat();
        try {
            
            callTomcat.callCommand(command);
            
//          The CATALINA_HOME environment variable is not defined correctly
//          This environment variable is needed to run this program

//出現這2行程式碼的話, 需要通過環境變數, 進行配置,步驟:右擊計算機屬性->高階系統設定->環境變數->新建->錄入變數名:CATALINA_HOME,變數值:D:\awgytools\apache-tomcat-8.0.44
        } catch (IOException e) {
            System.out.println("執行命令時出錯:" + e.getMessage());
        }
        
        

    }

    
    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);
         
    }