2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Alex Botev
  • 1,369
  • 2
  • 19
  • 34
  • See also http://stackoverflow.com/questions/1410741/want-to-invoke-a-linux-shell-command-from-java with the exact question and two potential answers. – Mihai Danila Jan 26 '13 at 05:04
  • 1
    For pities sake, start using `ProcessBuilder`! – Andrew Thompson Jan 26 '13 at 05:23
  • Thanks for the extra info, worked great. Am.. I havent used ProcessBuilder ever, cause I kinda stopped using java a while ago but might look at it. – Alex Botev Jan 26 '13 at 05:26
  • possible duplicate of [Using quotes and double quotes in Java Runtime.getRuntime().exec(...)](http://stackoverflow.com/questions/8413254/using-quotes-and-double-quotes-in-java-runtime-getruntime-exec) – Stephen C Jan 26 '13 at 05:27
  • You can also use ProcessBuilder. http://stackoverflow.com/a/7134525/2006412 – Govil Jan 26 '13 at 05:29

1 Answers1

4

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"});
that other guy
  • 116,971
  • 11
  • 170
  • 194