I am working on a program in Java designed to be used on a Linux environment that creates a new Java process that runs another Java class, but I am having trouble with it. I have finally fixed all my issues up to this. Invoking
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'" })
in my Java program returns
/bin/bash: /usr/lib/jvm/java-6-openjdk/jre/bin/java -classpath /home/kevin/workspace/Misc/bin HelloWorld: No such file or directory
in either stdout/stderr. If I try
Runtime.getRuntime().exec(new String[] { "/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'" })
I get a Java exception
Cannot run program "/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'": java.io.IOException: error=2, No such file or directory
...
Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
And finally, using a simple
Runtime.getRuntime().exec("/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'")
gives me a
-classpath: -c: line 0: unexpected EOF while looking for matching `''
-classpath: -c: line 1: syntax error: unexpected end of file
from stdout/stderr.
Meanwhile, creating a new one line .sh file (and assigning proper permissions) with only this (no #!/bin/bash at the top of the file)
/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'
gives the correct output with no errors.
I understand that the usage Runtime.exec is quite complicated to perfect, and I already solved some big problems I got from it before, but this problem just plain puzzles me (such as Runtime.exec's use of StringTokenizer screwing up any commands that have spaces in them, which is why I invoked the overload that accepts String arrays). However, I'm still getting problems with it and I don't understand why.
Your first attempt was almost correct.
Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "java -classpath /home/kevin/workspace/Misc/bin HelloWorld" })
You don't need the extra quoting because passing individual String
arguments effectively quotes it automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With