2010-03-17 1 views
7

자바 어플리케이션에서 쉘 명령어를 실행하는 것에 관한 문제가 있습니다. 여기에 코드입니다 :자바에서 쉘 명령어를 실행하십시오.

public String execRuntime(String cmd) { 

     Process proc = null; 
     int inBuffer, errBuffer; 
     int result = 0; 
     StringBuffer outputReport = new StringBuffer(); 
     StringBuffer errorBuffer = new StringBuffer(); 

     try { 
      proc = Runtime.getRuntime().exec(cmd); 
     } catch (IOException e) { 
      return ""; 
     } 
     try { 
      response.status = 1; 
      result = proc.waitFor(); 
     } catch (InterruptedException e) { 
      return ""; 
     } 
     if (proc != null && null != proc.getInputStream()) { 
      InputStream is = proc.getInputStream(); 
      InputStream es = proc.getErrorStream(); 
      OutputStream os = proc.getOutputStream(); 

      try { 
       while ((inBuffer = is.read()) != -1) { 
        outputReport.append((char) inBuffer); 
       } 

       while ((errBuffer = es.read()) != -1) { 
        errorBuffer.append((char) errBuffer); 
       } 

      } catch (IOException e) { 
       return ""; 
      } 
      try { 
       is.close(); 
       is = null; 
       es.close(); 
       es = null; 
       os.close(); 
       os = null; 
      } catch (IOException e) { 
       return ""; 
      } 

      proc.destroy(); 
      proc = null; 
     } 


     if (errorBuffer.length() > 0) { 
      logger 
        .error("could not finish execution because of error(s)."); 
      logger.error("*** Error : " + errorBuffer.toString()); 
      return ""; 
     } 


     return outputReport.toString(); 
    } 

하지만 난 명령처럼 간부 인하려고하면

/export/home/test/myapp -T "some argument" 

myapp와 내가 "some argument"으로 만 인수를 읽을 수 arguments.but 구분 "some argument" 두 가지로 읽습니다. 터미널에서이 명령을 직접 실행하면 성공적으로 실행됩니다.'"some argument"', ""some argument"", "some\ argument"을 시도했지만 저에게 적합하지 않았습니다. 어떻게이 논쟁을 하나의 논쟁으로 읽을 수 있을까요?

답변

16

exec 메소드의 오버로드는 인수에 대한 매개 변수를 별도로 제공한다는 것을 상기합니다. 그걸 사용해야합니다

예. 여기가

public Process exec(String[] cmdarray) 
      throws IOException 

그냥

+0

thx @midhat. 이것은 나를 위해 작동합니다. – Aykut

+0

[Runtime.exec()'가 다음과 같은 경우 :'Runtime.exec()'메소드와 관련된 함정 주위를 둘러보십시오.] (http://www.javaworld.com/article/2071275/core-java/when -runtime-exec --- won-t.html) 또는 미래를 보장하는 [검색 엔진 쿼리] (https://duckduckgo.com/?q=When+Runtime.exec+wont+Navigate+yourself+around+ 함정 + 관련 + + + Runtime.exec + 메소드). –

-3

먼저 문자열을
문자열 cmd를 구성하는 문자열 배열의 명령 줄 및 모든 인수 별도의 요소를하게됩니다 = "/ 수출/가정/시험/myapp와 -T \" 어떤 인자 \ "";
다음 cmd를 proc에서 실행하십시오.

+2

이것은 Aykut이 이미 지적한 것 이외에는 아무것도 없습니다. –

+0

@MiladNaseri Aykut의 실제 실수였던 따옴표를 올바르게 이스케이프한다는 점을 제외하고는. – Silveri