将参数从 java 程序传递到 bash 脚本,该脚本使用参数调用另一个 java 程序脚本、参数、程序、java

由网友(是时候拼搏了)分享简介:我想在我的 java 程序中执行一个 shell 脚本,并传递如下所示的参数:I want to executing a shell scripting in my java program passing a argument showed bellow:Runtime.getRuntime().exec("./...

我想在我的 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) 而不是 执行(字符串 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.

阅读全文

相关推荐

最新文章