2011-04-21 145 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(); 
    } 
相关问题