如何在java程序中将参数传递给shell脚本

我试图运行这个在运行时调用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代码中传递脚本的参数?

在最新版本的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 ,那么该方法的重载版本允许显式指定参数:

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

这是你可以尝试的非常简单的事情

 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(); } } }