天天看點

Java執行bat批處理檔案,并關閉cmd視窗

Java執行bat批處理檔案,并關閉cmd視窗

package com.baobaotao.test;  

import java.io.ioexception;  

public class cmdmain {  

    public static void main(string[] args) {  

        // 執行批處理檔案  

        string strcmd = "cmd /c start  e:\\run.bat";  

        runtime rt = runtime.getruntime();  

        process ps = null;  

        try {  

            ps = rt.exec(strcmd);  

        } catch (ioexception e1) {  

            e1.printstacktrace();  

        }  

            ps.waitfor();  

        } catch (interruptedexception e) {  

            // todo auto-generated catch block  

            e.printstacktrace();  

        int i = ps.exitvalue();  

        if (i == 0) {  

            system.out.println("執行完成.");  

        } else {  

            system.out.println("執行失敗.");  

        ps.destroy();  

        ps = null;  

        // 批處理執行完後,根據cmd.exe程序名稱  

        // kill掉cmd視窗  

        new cmdmain().killprocess();  

    }  

    public void killprocess() {  

        process p = null;  

            rt.exec("cmd.exe /c start wmic process where name='cmd.exe' call terminate");  

        } catch (ioexception e) {  

}