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

℡╲_俬逩灬. 提交于 2019-12-20 04:53:32

问题


I want to executing a shell scripting in my java program passing a argument showed bellow:

Runtime.getRuntime().exec("./test.sh " + "\\\"param1\\\"\\\"param2\\\"\\\"param3\\\"");

And the test.sh will call another java program passing the string argument like this:

another.jar \"param1\"\"param2\"\"param3\"

and finally the program anther.jar will interpret the argument in this format

another.jar "param1""param2""param3"

I'm a bit confuse with this bacause I can't deal correctly with escapes characters in this situation..kkk

I tried some strings formats in the first command but I didn't get the correct form.

Some help will be fine!

Thx!


回答1:


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.




回答2:


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]);
}


来源:https://stackoverflow.com/questions/4221444/passing-arguments-form-java-program-to-bash-script-that-call-another-java-progra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!