问题描述
我通常使用 java.lang.ProcessBuilder 和 java.lang.Process 来运行外部命令行程序,它适用于 run-and-done 命令.例如,这将在工作目录中运行带有参数myArg"的myProgram":
I normally use java.lang.ProcessBuilder and java.lang.Process to run external command line programs, and it works fine for run-and-done commands. For example, this would run "myProgram" with argument "myArg" in the working directory:
List<String> commandLine = new ArrayList<String>();
commandLine.add("myProgram");
commandLine.add("myArg");
ProcessBuilder builder = new ProcessBuilder(commandLine);
builder.redirectErrorStream(true);
Process process = builder.start();
然而,假设我想运行一个脚本或程序或具有交互式输入的东西(它在启动后提示我进行更多输入).我可以使用与上述类似的代码在 Java 中做到这一点,还是需要不同的方法?或者有什么图书馆可以帮助我解决这个问题?
However, say I wanted to run a script or program or something that had interactive input (it prompted me for more input after starting). Can I do that in Java with code similar to that above, or do I need a different approach? Or is there some library that can help me with this?
推荐答案
根据 文档 您应该能够重定向输入和输出流.这告诉它使用来自父进程的 System.in
/System.out
:
According to the documentation you should be able to redirect the input and output streams. This tells it to use the System.in
/System.out
from the parent process:
builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
如果你想写东西到进程的输入:
If you want to write things to the processes's input:
如果源是 Redirect.PIPE(初始值),则可以使用 Process.getOutputStream() 返回的输出流写入子进程的标准输入.如果源设置为任何其他值,则 Process.getOutputStream() 将返回空输出流.
这篇关于从 Java 运行交互式命令行应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!