1. 程式人生 > >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();
		}
		try {
			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() {
		Runtime rt = Runtime.getRuntime();
		Process p = null;
		try {
			rt.exec("cmd.exe /C start wmic process where name='cmd.exe' call terminate");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}