[英]How to pass parameter to shell script in java program
我试图运行在运行时调用外壳程序脚本的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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.