Java Runtime.exec woes on Linux

元气小坏坏 提交于 2019-12-03 10:09:05

问题


Hey guys. I'm 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'm having trouble with it. I've 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.


回答1:


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.



来源:https://stackoverflow.com/questions/5479461/java-runtime-exec-woes-on-linux

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