如何执行 Bash 命令并从 Java 收集输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4890175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:23:52  来源:igfitidea点击:

How do I execute Bash commands and collect the output from Java?

javabashprocesscommand

提问by Hyman H

How do I execute Bash commands and collect the output from Java?

如何执行 Bash 命令并从 Java 收集输出?

Hi all, basically I am writing a basic console app, and would like to be able to run commands from it, such as sudo***, halt, ifconfig, etc.

大家好,基本上我正在编写一个基本的控制台应用程序,并且希望能够从中运行命令,例如 sudo***、halt、ifconfig 等。

Any insight?.

任何见解?

回答by cheekoo

You can use processBuilderAPI for this purpose. See this example.

为此,您可以使用processBuilderAPI。请参阅此示例

回答by CloudyMarble

untested code:

未经测试的代码:

Runtime run = Runtime.getRuntime();
Process pr = run.exec(bashcommand);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

while ( ( String line ; line = buf.readLine() ) != null ) 
{
  System.out.println(line);
}