2

My Shell script named "hello"

#This is a shell script
echo "Hello Shell World!"

My Java Code,

Runtime.getRuntime().exec(new String[]{"./hello"});

My Java code is executed with no errors, but I do not see "Hello Shell World!" being printed on the terminal.

I believe my script is being executed since I do not get errors like, "hello cannot be executed, there is no such file or directory".

I am executing this on a Linux machine, Ubuntu. Thanks!

4

2 回答 2

2

当从 Java 运行外部程序时,输出不会到达(并且输入不会来自)Java 应用程序的终端。

外部程序(您的脚本)的输入和输出流(STDIN、STDOUT、STDERR)被定向到(从)InputStreams 和 OutputStreams,它们可以从您执行exec(...)

于 2013-09-17T18:48:14.727 回答
1

您应该使用阅读器来捕获命令的输出:

Process p=Runtime.getRuntime().exec(new String[]{"./hello"});
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null) {
    System.out.println(line);
    line=reader.readLine();
}
于 2013-09-17T18:48:02.580 回答