2009-03-04 3 views

답변

4

Runtime.getRuntime(). exec (...)가 필요합니다. a very extensive example을 참조하십시오 (처음 세 페이지를 읽는 것을 잊지 마십시오).

Runtime.exec은 입니다. 쉘이 아닙니다.; 당신이 쉘 스크립트를 실행하고자하는 경우 (나는/빈 경로에 항상 의심 있지만) 명령 줄 당신이 필요로하는 쉘 바이너리 완전한 이름입니다

/bin/bash scriptname 

과 같을 것이다. 당신은

myshell> foo.sh 

실행,

Runtime.getRuntime.exec("foo.sh"); 

또한 Runtime.exec의 당신이 첫 번째 예에서 실행중인 쉘에서 이미으로 실행하지만,하지 않을 경우 가정 할 수 없다.

A는 the previously mentioned article에서 예를 들어, mosly 잘라 내기 및 과거 (내 리눅스 머신 (TM)에서 작동을) 테스트 :

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
public class ShellScriptExecutor { 

    static class StreamGobbler extends Thread { 
     InputStream is; 

     String type; 

     StreamGobbler(InputStream is, String type) { 
      this.is = is; 
      this.type = type; 
     } 

     public void run() { 
      try { 
       InputStreamReader isr = new InputStreamReader(is); 
       BufferedReader br = new BufferedReader(isr); 
       String line = null; 
       while ((line = br.readLine()) != null) 
        System.out.println(type + ">" + line); 
      } catch (IOException ioe) { 
       ioe.printStackTrace(); 
      } 
     } 
    } 


    public static void main(String[] args) { 
     if (args.length < 1) { 
      System.out.println("USAGE: java ShellScriptExecutor script"); 
      System.exit(1); 
     } 

     try { 
      String osName = System.getProperty("os.name"); 
      String[] cmd = new String[2]; 
      cmd[0] = "/bin/sh"; // should exist on all POSIX systems 
      cmd[1] = args[0]; 

      Runtime rt = Runtime.getRuntime(); 
      System.out.println("Execing " + cmd[0] + " " + cmd[1]); 
      Process proc = rt.exec(cmd); 
      // any error message? 
      StreamGobbler errorGobbler = new StreamGobbler(proc 
        .getErrorStream(), "ERROR"); 

      // any output? 
      StreamGobbler outputGobbler = new StreamGobbler(proc 
        .getInputStream(), "OUTPUT"); 

      // kick them off 
      errorGobbler.start(); 
      outputGobbler.start(); 

      // any error??? 
      int exitVal = proc.waitFor(); 
      System.out.println("ExitValue: " + exitVal); 
     } catch (Throwable t) { 
      t.printStackTrace(); 
     } 
    } 
} 
+0

스크립트가 'chmod + x'd이고 첫 번째 줄이 #!/bin/sh이면 직접 실행할 수 있습니다. – vrdhn

+0

또한 Runtime.exec()에? 스크립트의 첫 줄을 검사하여 #으로 시작하는지 확인하는 쉘이라고 생각했습니다. 새로운 것을 배우는 것은 항상 좋은 일입니다. – extraneon

3

쉘 스크립트 test.sh 코드

#!/bin/sh 
echo "good" 

자바 코드에 쉘 스크립트 test.sh를 실행하십시오.

 try { 
      Runtime rt = Runtime.getRuntime(); 
      Process pr = rt.exec(new String[]{"/bin/sh", "./test.sh"}); 

      BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); 
      String line = ""; 
      while ((line = input.readLine()) != null) { 
       System.out.println(line); 
      } 
     } catch (Exception e) { 
      System.out.println(e.toString()); 
      e.printStackTrace(); 
     } 
관련 문제