本文介绍了如何在java程序中将参数传递给shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试运行这个在运行时调用shell脚本的java代码。
i am trying to run this java code that calls the shell script on runtime.
当我在终端中运行脚本时我将参数传递给脚本
when i run the script in terminal i am passing argument to script
代码:
./test.sh argument1java code:
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(); } } }如何为脚本传递参数在java代码中?
How to pass argument for script in java code?
推荐答案在最新版本的Java中创建进程的首选方法是使用 ProcessBuilder class这使得这很简单:
The preferred way to create processes in recent versions of Java is to use the ProcessBuilder class, which makes this very simple:
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 无论出于何种原因,都有该方法的重载版本,允许明确指定参数:
But if you do want to/need to use Runtime.exec for whatever reason, there are overloaded versions of that method that allow the arguments to be specified explicitly:
Process proc = Runtime.getRuntime().exec(new String[]{"./test.sh", "kstc-proc"});更多推荐
如何在java程序中将参数传递给shell脚本
发布评论