2011-04-21 2 views
2

자바 코드 내에서 (java -classpath path/file.jar classname을 사용하여) jar 파일의 어딘가에있는 클래스를 호출합니다.자바 명령을 수행 할 때 오류 메시지를받는 방법은 무엇입니까?

이 명령은 정상적으로 작동하지만 명령이 올바른 형식 인 경우에만 작동합니다. 내가 실수를하면 getRuntime() .exect (명령) 그냥 아무 말도하지 않습니다. 나는 일하는 명령을 가지고있다. 명령이 작동하지 않을 때 오류 메시지를 보내고 싶습니다. 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

:.

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

다른 스트림들로부터의 입력을 처리하는 것이 그 호출 (readLine 등) 호출을 차단하고 있기 때문에 (다른 스레드에서 수행하는 것이 좋다를

+0

어쨌든 프로세스가 종료 될 때까지 기다리는 것처럼 보입니다. –

+0

나는 동의하지만 같은 스레드에서 두 스트림을 병렬로 읽을 수는 없다. – MByD

+0

@MByD 왜 안 되니? – corsiKa

2

Process.getErrorStream 당신이 원하는 아닌가요 감사합니다? getErrorStream 사용함으로써

3

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(); 
    } 
:

여기에 오류를 출력하는 코드의 좀 더 완벽한 조각 프로세스/런타임를 통해 일부 command을 실행에받은입니다

관련 문제