2010-09-27 141 views
2

我試圖遠程執行一個.bat文件和執行的代碼下面幾行後卡住:while循環的ProcessBuilder得到得到一個錯誤

ProcessBuilder processBuilder = new ProcessBuilder(command); 
    final Process process = processBuilder.start(); 

    InputStream stderr = process.getErrorStream(); 
    InputStreamReader isr = new InputStreamReader(stderr); 
    BufferedReader br = new BufferedReader(isr); 
    String line = null; 


    while ((line = br.readLine()) != null) { 
     System.out.println(line); 

    } 
    process.waitFor(); 
    System.out.println("Waiting ..."); 

    System.out.println("Returned Value :" + process.exitValue()); 

,但我的程序卡住內。 它顯示的錯誤是:

CMD.EXE was started with the above path as the current directory. 
UNC paths are not supported. Defaulting to Windows directory. 

它永不熄滅的同時loop.But它成功地執行腳本。 任何形式的幫助表示讚賞。謝謝

回答

3

你需要確保你也處理stderr,你應該在不同的線程中處理兩個流。

閱讀this並確保你按照所有的意見。

編輯:看看你寫的代碼,你似乎已經從這篇精確的文章中複製了代碼。實際上,它看起來像清單4.3(MediocreExecJavac.java)。

+2

或者,調用'processBuilder.redirectErrorStream(true);'將進程的標準錯誤重定向到它的標準輸出。那麼你只需要從'process.getInputStream()'讀取。 – 2010-09-27 22:02:27

2

在.start()和getInputStream()之前添加redirectErrorStream(true)。這將讀取stderr並將其與stdout合併爲一個可以使用getInputStream()讀取的響應。

ProcessBuilder processBuilder = new ProcessBuilder(command); 
    processBuilder.redirectErrorStream(true); 
    final Process process = processBuilder.start(); 

    InputStream stderr = process.getInputStream(); 
    InputStreamReader isr = new InputStreamReader(stderr); 
    BufferedReader br = new BufferedReader(isr); 
    String line = null; 


    while ((line = br.readLine()) != null) { 
     System.out.println(line); 

    } 
    process.waitFor(); 
    System.out.println("Waiting ..."); 

    System.out.println("Returned Value :" + process.exitValue());