的Java的Runtime.exec愁楚在Linux [英] Java Runtime.exec woes on Linux

查看:245
本文介绍了的Java的Runtime.exec愁楚在Linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,伙计们。我工作在Java中设计为能在创建运行另一个Java类一个新的Java程序在Linux环境中使用的程序,但我与它有麻烦。我终于修好了我的所有问题到这一点。调用

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'" })

在我的Java程序返回

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'" })

我得到一个Java异常

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'")

给我一个

-classpath: -c: line 0: unexpected EOF while looking for matching `''
-classpath: -c: line 1: syntax error: unexpected end of file

从标准输出/标准错误。

from stdout/stderr.

同时,创建一个新的一行sh文件(和分配适当的权限),只有这(无#!/斌/ bash的在文件的顶部)

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.

据我所知,使用的Runtime.exec是相当复杂的完美,我已经解决了我以前从中得到了一些大的问题,但这个问题只是简单的让我为难,(如的Runtime.exec的使用StringTokenizer类的事情搞砸任何命令有空格的,这就是为什么我调用接受字符串数组)的过载。不过,我仍然获得与它的问题,我不明白为什么。

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.

这篇关于的Java的Runtime.exec愁楚在Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆