2016-07-14 3 views
0

이 코드는 명령 줄을 실행해야하지만 특정 명령에서만 작동합니다. 예를 들어, 개방 및 jar 파일을 실행하기위한 작동하지만,이 명령을 실행 할 수없는 것 :Java 프로그램에서 명령 실행

echo 'Hello World' > HelloWorld.txt 

하여 HelloWorld라는 txt 파일을 작성해야합니다. 누군가 문제를 파악하는 데 도움을 줄 수 있습니까?

public static void command(String command) { 
    try { 
     Process p = Runtime.getRuntime().exec(command); 
     BufferedReader in = new BufferedReader(
          new InputStreamReader(p.getInputStream())); 
     String line = null; 
     while ((line = in.readLine()) != null) { 
      System.out.println(line); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+1

Windows 또는 Linux에 있습니까? "실제"명령과 "쉘 내장"의 차이점을 알고 있습니까? 또한 자바로 서브 프로세스를 시작하는 현대적인 방법이기 때문에'ProcessBuilder'를 읽어보아야합니다. –

답변

0

문제는 당신이 당신의 명령에 >을 가지고 exec 함수에 문자열로 입력 한 것입니다. 나는 exec 명령이 그러한 명령문을 실행할 수없는 이유를 정확히 알지 못하지만 파이프 | 또는 리디렉션 > 등이있는 경우 명령이 문자열 입력으로 주어질 때이를 처리 할 수 ​​없습니다. 당신이해야 할 일은

public static void command(String command) { 
    try { 
     String[] cmd = {"/bin/sh", "-c" , command }; // you have to input an string array your command will be executed in a new shell. 
     Process p = Runtime.getRuntime().exec(cmd); 
     BufferedReader in = new BufferedReader(
          new InputStreamReader(p.getInputStream())); 
     String line = null; 
     while ((line = in.readLine()) != null) { 
      System.out.println(line); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

새로운 쉘 프로세스가 반환하기 전에이 실행하세요 (리디렉션 포함)/빈/sh와 전체 명령에 의해 작성된 얻을 것이다 다음 예와 같이 별도의 스크립트로 실행됩니다.

+0

대단히 감사합니다! –

+0

@ S.Elm 당신을 환영합니다 .. .. :) – printfmyname

관련 문제