问题描述
我想在我的 java 程序中执行一个 shell 脚本并传递一个如下所示的参数:
I want to executing a shell scripting in my java program passing a argument showed bellow:
Runtime.getRuntime().exec("./test.sh " + "\\\"param1\\\"\\\"param2\\\"\\\"param3\\\"");
并且 test.sh 将调用另一个传递字符串参数的 java 程序,如下所示:
And the test.sh will call another java program passing the string argument like this:
another.jar \"param1\"\"param2\"\"param3\"
最后程序 anther.jar 将以这种格式解释参数
and finally the program anther.jar will interpret the argument in this format
another.jar "param1""param2""param3"
我对此有点困惑,因为在这种情况下我无法正确处理转义字符..kkk
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.
一些帮助会很好!
谢谢!
推荐答案
我认为你最好使用 exec(String[] cmdarray) 而不是 exec(String cmd).这是因为 exec(String cmd) 通过 StringTokenizer,在分解命令行参数时根本不注意双引号.
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.
试试这样的:
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);
参数值内的字符不需要引用或转义,除非 Java 源代码字符串文字可能需要转义.
Characters inside the param values should not need quoting or escaping, except insofar as Java source code string literals may require escaping.
这篇关于将参数从 java 程序传递给 bash 脚本,该脚本使用参数调用另一个 java 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!