2014-04-19 3 views
1

쉘을 통해 실행하려고하는 perl 스크립트가 있습니다. 일반적인 유닉스 쉘 호출은 do /home/projects/bumble/script.pl --input/home/input/input.txt> /home/output/output.txt입니다.ProcessBuilder를 사용하여 Java를 통해 perl 스크립트를 실행하십시오.

String command = "/home/projects/bumble/script.pl --input /home/input/input.txt > /home/output/output.txt"; 
File directory = new File("/home/projects/bumble"); 
runCommand(command,directory); 

내가 얻을 예외는 다음과 같습니다 : 때 java.io.IOException : ... 실행할 수 없습니다 나는이 전화

public void runCommand(String command, File directory) { 
    final ProcessBuilder pb = new ProcessBuilder(command); 
    pb.directory(directory); 
    final Process process = pb.start(); 
    if(process.waitFor() != 0) { 
     throw new RuntimeException("ERROR"); 
    } 
} 

: 나는 함수를 쓴 자바에서이 작업을 수행하려면

프로그램 오류 = 2, 그런 파일이나 디렉토리 없음

여기서 주목 : java.io.IOException: Cannot run program error=2, No such file or directory은 완전한 입력이 주어진 완전히 다른 디렉토리에 프로그램을 실행하는 것이 fa il. /home/projects/bumble/script.pl --input/home/input/input.txt 명령을 실행해도 동일한 오류가 발생합니다. 쉘을 통해 직접 실행하면 작동합니다. 내가 누락되었거나 잘못하고있는 것이 있습니까?

+0

나는'script.pl'의 첫 번째 줄은 '#는/usr/빈/perl' 또는 뭔가 비슷한 것 같은데요? 'ProcessBuilder'가 이것을 이해할 수있을 지 모르겠다. 그러므로'ProcessBuilder'가 쉘을 실행하도록'ProcessBuilder'를 갖도록해야한다. 즉,'String command = "sh/home/projects/...'(또는'/ bin/sh/home/projects/... '). 필자는 Linux/Unix에서 Java를 사용한 적이 없기 때문에 이에 대해서는 잘 모르겠지만 시도해 볼 가치가 있습니다. – ajb

+0

예, 첫 번째 줄입니다. 고마워, 나는 그것을 시도 할 것이다. – Niru

+0

여전히 오류는 있지만/bin/sh를 찾을 수 없습니다. – Niru

답변

1

Runtime.exec의() 트랩 : 코드와 http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=3

2 문제 : 출력이없이 별도로 처리해야

String[] command = {"perl", "/home/projects/bumble/script.pl", "--input", "/home/input/input.txt"} 

: 같은 명령 문자열 []로 세분화되어야 리디렉션 ">" 이렇게하기 위해, ProcessBuilder는 Redirect를 가지고 있습니다. http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.Redirect.html

는 프로그래밍 기능은 다음과 같습니다!

public static void runCommand(final String[] command, final File directory, final File output) throws IOException, InteruptException { 
    final ProcessBuilder pb = new ProcessBuiler(command); 
    pb.redirectErrorStream(true); //optional; easier for this case to only handle one stream 
    pb.redirectOutput(Redirect.to(output)); 
    final Process p = pb.start(); 

    if(p.waitFor != 0) { 
     //throw an exception/return error message 
    } 
} 
관련 문제