.bat文件執行的時候,如果有屏幕輸出,就必須要讀取這個輸出,如果不讀取,就會導致這個bat不會被執行下去。所以,只要用個InputStream把輸出讀出來就ok了。
另外,誰也不能保證Process運行以后系統的PATH到底是什么,所以建議寫上調用的bat的絕對路徑
import java.io.IOException;
import java.io.InputStream;
public class TestProcess {
? ? public static void main(String[] args) {
? ? ? ? ? String command = "c:\\aaa.bat";
? ? ? ? ? try {
? ? ? ? ? ? ? ? Process child = Runtime.getRuntime().exec(command);
? ? ? ? ? ? ? ? InputStream in = child.getInputStream();
? ? ? ? ? ? ? ? int c;
? ? ? ? ? ? ? ? while ((c = in.read()) != -1) {
? ? ? ? ? ? ? ? ? ? System.out.print(c);//如果你不需要看輸出,這行可以注銷掉
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? in.close();
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? child.waitFor();
? ? ? ? ? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? ? ? ? ? // TODO Auto-generated catch block
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? System.out.println("done");
? ? ? ? ? } catch (IOException e) {
? ? ? ? ? ? ? ? // TODO Auto-generated catch block
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? }
? ? }
}