[英]problem while running shell script using java
我在/tmp/padm
文件夹中有一个名为test.sh
的shell脚本。 在那个shell脚本中,我只有一个语句
echo "good"
我正在尝试使用Java代码运行shell脚本。
String cmd=("/tmp/padm/.test.sh");
Runtime rt = Runtime.getRuntime();
Process pr=rt.exec(cmd);
但我的问题是我无法看到“好”这是shell脚本的输出。
如何让脚本运行?
您可以使用以下代码获取命令输出。 希望这可以帮助。
Process process = Runtime.getRuntime().exec(cmd);
String s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(process
.getInputStream()));
while ((s = br.readLine()) != null)
{
s += s + "\n";
}
System.out.println(s);
BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while (br2.ready() && (s = br2.readLine()) != null)
{
errOutput += s;
}
System.out.println(errOutput);
试试这个,肯定会有效。
Shell脚本test.sh代码
#!/bin/sh
echo "good"
Java代码执行shell脚本test.sh
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]{"/bin/sh", "/tmp/padm/.test.sh"});
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
那不行。 您必须在脚本的第一行添加“hash bang”,告诉Linux它必须使用合适的解释器(例如bash)来解释脚本,或者通过Java显式地通过bash运行它。
当你说“在终端上”是什么意思? 如果要查看进程中的输出/错误,则需要使用:
process.getErrorStream();
process.getOutputStream();
除此之外,从使用Runtime.exec
调用shell脚本我可以看到没有问题
process.getErrorStream();
process.getOutputStream();
是oxbow_lakes指出的正确方法。
另外,请确保使用shell脚本位置作为参数执行/bin/sh
。
这是需要使用样本java代码运行一个shellscript的副本。
我的答案中的示例程序确实打印出标准错误和标准输出(示例程序稍后添加)。
请注意,streamGobblers在不同的线程中运行,以防止由于完整的输入/输出缓冲区而导致执行问题。
如果您希望您可以让StreamGobblers将输出存储在列表中,并在执行该过程后检索列表,而不是直接将其转储到stdout上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.