2011-04-21 34 views
2

我在我的java代碼中調用了一個位於jar文件中的類(使用java -classpath path/file.jar classname)。如何在執行java命令時得到錯誤信息?

這個工作很好,但只有當命令格式正確。如果我犯了一個錯誤,getRuntime().exect(command)就是什麼也沒說。貝婁我有工作命令調用。當命令不起作用時,我想獲得錯誤消息。如果我在cmd(windows)中犯了一個錯誤,我會得到一個適當的錯誤,我可以修復它。但不是在我的Java應用程序。

我留下了一個'if(input.ready())',因爲如果我不知道程序在命令行不正確的時候死機。執行'input.readLine()'時會發生這種情況。

 // Execute a command with an argument that contains a space 
     String[] genKOSCommand = new String[] { 
       "java", 
       "-classpath", 
       Config.XDSI_TEST_KIT_HOME + "/xdsitest/lib/xdsitest.jar;" 
         + Config.XDSI_TEST_KIT_HOME + "/xdsitest/classes", 
       "ca.etsmtl.ihe.xdsitest.docsource.SimplePublisher", "-k", 
       "C:/Softmedical/Viewer_Test/xdsi-testkit-2.0.4/xdsihome/usr/data/image14.dcm" }; 

     Process child = Runtime.getRuntime().exec(genKOSCommand); 

     BufferedReader input = new BufferedReader(new InputStreamReader(
       child.getInputStream()), 13107200); 

     String line = null; 

     if (input.ready()) { 
      while ((line = input.readLine()) != null) { 
       System.out.println(line); 
      } 

      try { 
       child.waitFor(); 
      } catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 

對如何從執行的命令中獲取錯誤有任何建議嗎?

謝謝

回答

3

通過使用getErrorStream:

BufferedReader errinput = new BufferedReader(new InputStreamReader(
       child.getErrorStream())); 

當處理來自不同流的輸入端,最好是做在不同的線程(因爲那些呼叫(readLine等)被阻塞調用

+0

看起來他希望等待過程終止。 – 2011-04-21 19:00:45

+0

我同意,但你不能在同一個線程中並行讀取兩個流。 – MByD 2011-04-21 19:01:29

+0

@MByD,爲什麼不呢? – corsiKa 2011-04-21 19:08:58

3

下面的代碼以打印出錯誤的詳細一點完整片經由過程/運行時一旦運行一些command接收:

final String command = "/bin/bash -c cat foo.txt | some.app"; 
Process p; 
    try { 
     p = Runtime.getRuntime().exec(command); 
    } catch (final IOException e) { 
     e.printStackTrace(); 
    } 

    //Wait to get exit value 
    try { 
     p.waitFor(); 
     final int exitValue = p.waitFor(); 
     if (exitValue == 0) 
      System.out.println("Successfully executed the command: " + command); 
     else { 
      System.out.println("Failed to execute the following command: " + command + " due to the following error(s):"); 
      try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getErrorStream()))) { 
       String line; 
       if ((line = b.readLine()) != null) 
        System.out.println(line); 
      } catch (final IOException e) { 
       e.printStackTrace(); 
      }     
     } 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    }