2013-01-12 48 views
0

如何在執行二進制文件時得到錯誤信息Runtime在java中運行二進制文件得到異常錯誤

我的代碼是:

Runtime localRuntime = Runtime.getRuntime(); 
String strExec = "myBinary -s -a myconfigbinary.conf"; 
try { 
    localRuntime.exec(strExec); 
    System.out.println("Success execute."); 
} catch (IOException e) { 
    System.out.println(e.getMessage().toString());  
} 

我的代碼是如此,在文件不存在我只得到了異常錯誤。但如果我在計算機上使用控制檯運行時,因配置文件中的錯誤而無法工作,或者導致二進制文件未運行,但我仍然收到消息Success execute.

我的問題是我想得到錯誤消息,就像當我在電腦上的控制檯上出現錯誤。在這種情況下如何使用正確的異常?

謝謝。

回答

1

您可以檢查像

Process process=localRuntime.exec(strExec); 
process.waitFor(); 
InputStream errorStream = process.getErrorStream(); 
1

錯誤流你也應該捕捉java的過程中ErrorStream,作爲

try { 
    Process proc = localRuntime.exec(strExec); 
    InputStream stderr = proc.getErrorStream(); 
    InputStreamReader is = new InputStreamReader(stderr); 
    BufferedReader br = new BufferedReader(is); 
    String line = null; 
    while ((line = br.readLine()) != null) 
      System.out.println(line); 
    int exitVal = proc.waitFor(); 
    System.out.println("Process exitValue: " + exitVal); 
} catch (Throwable t) { 
    t.printStackTrace(); 
} 

如果從exec'd過程中的錯誤去stdout ,您可能還需要爲stdout執行上述操作。

+0

嗨,謝謝。但沒有成功,仍然獲得消息成功 –

+0

獲取堆棧和無載視圖proc.waitFor(); –

相關問題