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开发者_StackOverflow.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!
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]);
}
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.
精彩评论