我试图用java来运行一些bash脚本并将终端输出存储在一个字符串中。但是,有很多命令不能以这种方式工作。它一直显示命令未找到,但我可以在终端正确运行这些命令,ex节点 - 版本,去 - 版本。我想是路径问题,但不知道如何解决它。java运行bash脚本,找不到命令
另一个问题,当我运行“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显然是这样做的... – EagleRainbow
@VishalKamat我在下面回复它。感谢您的好评和有用的评论! – user3390980