我正在尝试运行这个在运行时调用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代码中传递脚本的参数?
答案 0 :(得分: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"});
答案 1 :(得分: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();
}
}
}