Passing arguments form java program to bash script that call another java programa with the arguments

拥有回忆 提交于 2019-12-02 07:11:05

I think you would be better off using exec(String[] cmdarray) instead of exec(String cmd). This is because exec(String cmd) tokenizes the arguments via StringTokenizer, which pays no attention at all to double quotes when breaking up the command line arguments.

Try something like this:

ArrayList<String> argList = new ArrayList<String>();
argList.add("param1");
argList.add("param2");
argList.add("param2");
String[] args = argList.toArray(new String[argList.size()]);
Runtime.getRuntime().exec("mycommand", args);

Characters inside the param values should not need quoting or escaping, except insofar as Java source code string literals may require escaping.

Use ProcessBuilder. Nothing special needs to be done with the parameters, they'll just trickle through.

//ProcessBuilder pb = new ProcessBuilder("test.sh", "param1", "param2", "param3");
ProcessBuilder pb = new ProcessBuilder("test.sh", "param1 " + "param2 " + "param3");
pb.start();

In test.sh:

java -jar program2 $1 # Or however you want to call it.

In program2.java

public static void main(String[] args)
{
   System.out.println(args[0]);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!