Java Runtime.exec() arguments on Linux

☆樱花仙子☆ 提交于 2019-11-28 09:56:03

问题


Okay so here is the problem: I have 3 classes MyClass1 and MyClass2 and ExecClass. I go to my command prompt and do this:

$java MyClass1 -exec "java MyClass2 arg1 arg2"

which works perfectly. Now in ExecClass I have the following line:

Runtime.getRuntime().exec("java MyClass1 -exec \"java MyClass2 arg1 arg2\"");

Problem is if you print the second string its exactly the same as the first, but when my ExecClass runs it MyClass1 complains: Unrecognized argument arg1 and fails. After a bit of debugging I found out that in the first case when I'm calling directly from the terminal the whole string in the quotes is 1 argument (arg[1]), where in the second case the arg.length = 5 and it basically splits them... for some unkown reason to me. I just need to know a workarround that if someone knows, aka my Runtime.exec() to works. PS: On my Windows machine such problem does not occur only on the linux. It's a ubuntu destrution Kernel: 2.6.32-279.14.1.el6.x86_64.


回答1:


Runtime.exec, unlike system()-like functions in other languages, does not invoke a shell to parse the command (and double quoted strings are a shell feature).

To split the string the way you want it, use the Runtime.exec that accepts a String array:

Runtime.getRuntime().exec(new String[] { "java", "MyClass1", "-exec", "java MyClass2 arg1 arg2"});


来源:https://stackoverflow.com/questions/14533954/java-runtime-exec-arguments-on-linux

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