2013-06-03 40 views
0

我试图运行调用运行时的shell脚本这个Java代码shell脚本。如何通过参数在java程序

当我在终端运行脚本我传递参数给脚本

代码:

./test.sh argument1 

java代码:

public class scriptrun 
    { 
     public static void main(String[] args) 
      { 
      try 
       { 
        Process proc = Runtime.getRuntime().exec("./test.sh"); 
        System.out.println("Print Test Line."); 
       } 
       catch (Exception e) 
       { 
        System.out.println(e.getMessage()); 
        e.printStackTrace(); 
       } 
      } 
    } 

如何通过论证在java代码脚本?

+1

改为使用['ProcessBuilder'](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html)。的 – NilsH

+0

可能重复的[如何执行与参数命令?](http://stackoverflow.com/questions/7134486/how-to-execute-command-with-parameters) – Raedwald

回答

3

的首选方法来创建在最新版本的Java程序是使用ProcessBuilder类,这使得这个很简单:

ProcessBuilder pb = new ProcessBuilder("./test.sh", "kstc-proc"); 
// set the working directory here for clarity, as you've used a relative path 
pb.directory("foo"); 
Process proc = pb.start(); 

但是,如果你想/需要使用Runtime.exec无论出于何种原因,有overloaded versions of that method允许的参数被明确指定:

Process proc = Runtime.getRuntime().exec(new String[]{"./test.sh", "kstc-proc"}); 
0

这里是很简单的东西,你可以尝试

public class JavaRunCommandExample { 

    public static void main(String[] args) { 

     Runtime r = Runtime.getRuntime(); 
     Process p = null; 
     String cmd[] = {"./test.sh","argument1"}; 

     try { 
      p = r.exec(cmd); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
}