简体   繁体   English

从Java调用简单的Shell脚本不起作用

[英]Calling a simple shell script from java is not working

My Shell script named "hello" 我的Shell脚本名为“ hello”

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

My Java Code, 我的Java代码,

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

My Java code is executed with no errors, but I do not see "Hello Shell World!" 我的Java代码已正确执行,但是看不到“ 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. 我正在Linux机器Ubuntu上执行此操作。 Thanks! 谢谢!

When running an external program from Java the output does not go to (and the input does not come from) the Java application's terminal. 从Java运行外部程序时,输出不会到达Java应用程序的终端(输入也不来自Java应用程序的终端)。

The input and output streams (STDIN, STDOUT, STDERR) to the external program (your script) are directed to (from) InputStreams and OutputStreams that are accessible from the Java Process that is created when you do the exec(...) 到外部程序(您的脚本)的输入和输出流(STDIN,STDOUT,STDERR)被定向到(从)当您执行exec(...)时创建的Java 流程可访问的InputStreams和OutputStreams exec(...)

You should use a reader to capture the output of the command: 您应该使用阅读器捕获命令的输出:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM