gpt4 book ai didi

java - 从 java 在终端中运行脚本

转载 作者:行者123 更新时间:2023-12-01 13:49:12 24 4
gpt4 key购买 nike

我正在使用以下方法在 java 程序中运行脚本:

 Runtime.getRuntime().exec()

我可以使用它打开终端应用程序

如果我发出命令来运行脚本。它正在发生,但我无法在终端中获取日志。我正在使用MAC。我想获取终端中的日志。

最佳答案

您可以使用 Process 变量来获取该命令的返回内容,并使用诸如 getInputStream()、getOutputStream()、getErrorStream() 等方法。示例:

    Process p = null;
try {
p = Runtime.getRuntime().exec(....your stuff here)
p.getOutputStream().close(); // close stdin of child

InputStream processStdOutput = p.getInputStream();
Reader r = new InputStreamReader(processStdOutput);
BufferedReader br = new BufferedReader(r);
String line;
while ((line = br.readLine()) != null) {
//System.out.println(line); // the output is here
}

p.waitFor();
}
catch (InterruptedException e) {
...
}
catch (IOException e){
...
}
finally{
if (p != null)
p.destroy();
}

关于java - 从 java 在终端中运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20095841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com