Java Runtime.exec在Linux上遇到了麻烦

Kev*_*Jin 5 java linux bash runtime exec

大家好.我正在开发一个Java程序,用于在Linux环境中使用,该环境创建一个运行另一个Java类的新Java进程,但我遇到了麻烦.我终于解决了所有问题.调用

Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'" })
Run Code Online (Sandbox Code Playgroud)

在我的Java程序中返回

/bin/bash: /usr/lib/jvm/java-6-openjdk/jre/bin/java -classpath /home/kevin/workspace/Misc/bin HelloWorld: No such file or directory
Run Code Online (Sandbox Code Playgroud)

在stdout/stderr中.如果我试试

Runtime.getRuntime().exec(new String[] { "/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'" })
Run Code Online (Sandbox Code Playgroud)

我得到一个Java异常

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
Run Code Online (Sandbox Code Playgroud)

最后,使用简单

Runtime.getRuntime().exec("/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'")
Run Code Online (Sandbox Code Playgroud)

给了我一个

-classpath: -c: line 0: unexpected EOF while looking for matching `''
-classpath: -c: line 1: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

来自stdout/stderr.

同时,创建一个新的一行.sh文件(并分配适当的权限)只有这个(文件顶部没有#!/ bin/bash)

/bin/bash -c 'java -classpath /home/kevin/workspace/Misc/bin HelloWorld'
Run Code Online (Sandbox Code Playgroud)

给出正确的输出而没有错误.

我知道Runtime.exec的用法非常复杂,而且我已经解决了之前从中得到的一些大问题,但这个问题让我感到很困惑(例如Runtime.exec使用StringTokenizer搞砸任何有空格的命令在它们中,这就是我调用接受String数组的重载的原因).但是,我仍然遇到问题,我不明白为什么.

gee*_*aur 11

你的第一次尝试几乎是正确的.

Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "java -classpath /home/kevin/workspace/Misc/bin HelloWorld" })
Run Code Online (Sandbox Code Playgroud)

您不需要额外的引用,因为传递单个String参数可以自动引用它.

  • 先生,你是最伟大的.我简直不敢相信答案就这么简单!非常感谢你,我从未想过会做那样的事情. (2认同)