【发布时间】:2016-09-27 13:52:50
【问题描述】:
我尝试使用 java 来运行一些 bash 脚本并将终端输出存储在一个字符串中。但是,有很多命令不能以这种方式工作。它一直显示找不到命令,但我可以在终端中正确运行这些命令,ex node --version,go --version。我猜是路径问题,但不知道如何解决。
另一个问题,当我运行“python --version”时,它显示“Python 2.7.10”,但它在 getErrorStream 中。谁能给我一些提示?
public static void runscript() throws IOException {
Runtime rt = Runtime.getRuntime();
String[] commands = { "/bin/bash", "-c", "node --version" };
Process proc = null;
try {
proc = rt.exec(commands);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
【问题讨论】:
-
您能否尝试提供命令的完整路径而不仅仅是名称。 “哪个节点”会给你路径。尝试在您的 java 代码中使用它。同样值得从 java 中回显 $PATH 以查看与终端的区别
-
关于“getErrorStream”:如您所知,程序可以使用两个流来打印信息。程序本身决定使用哪一个。尽管有相当多的官方指导在哪里打印什么,但这通常没有准确处理。在你的情况下,python 显然是这样做的......
-
@VishalKamat 我在下面回复它。感谢您的精彩和有用的评论!
-
@EagleRainbow 我不知道。我以为这是我喜欢的路径设置错误。感谢分享。
标签: java bash scripting command