bash 如何在java程序中将参数传递给shell脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16893929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass parameter to shell script in java program
提问by milano
i am trying to run this java code that calls the shell script on runtime.
我正在尝试运行这个在运行时调用 shell 脚本的 java 代码。
when i run the script in terminal i am passing argument to script
当我在终端中运行脚本时,我将参数传递给脚本
code:
代码:
./test.sh argument1
java code:
代码:
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();
}
}
}
How to pass argument for script in java code?
如何在java代码中为脚本传递参数?
回答by Andrzej Doyle
The preferred way to create processes in recent versions of Java is to use the ProcessBuilderclass, which makes this very simple:
在最新版本的 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();
But if you do want to/need to use Runtime.execfor whatever reason, there are overloaded versions of that methodthat allow the arguments to be specified explicitly:
但是,如果您Runtime.exec出于某种原因确实想/需要使用,则该方法有重载版本,允许显式指定参数:
Process proc = Runtime.getRuntime().exec(new String[]{"./test.sh", "kstc-proc"});
回答by Divya Paliwal
Here is something very simple you can try
这是您可以尝试的非常简单的事情
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();
}
}
}

