天天看点

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) {  

}