问题描述
如果我通过 Java 的 ProcessBuilder 类,我可以完全访问该进程的标准输入、标准输出和标准错误流,如 Java InputStreams
和 OutputStreams
.但是,我找不到将这些流无缝连接到 System.in
、System.out
和 System.err
的方法.
If I start a process via Java's ProcessBuilder class, I have full access to that process's standard in, standard out, and standard error streams as Java InputStreams
and OutputStreams
. However, I can't find a way to seamlessly connect those streams to System.in
, System.out
, and System.err
.
可以使用 redirectErrorStream()
来获取包含子进程的标准输出和标准错误的单个 InputStream
,然后循环遍历并通过我的标准发送出来——但我找不到办法让用户输入到流程中,就像我使用 C system()
调用一样.
It's possible to use redirectErrorStream()
to get a single InputStream
that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C system()
call.
这在 Java SE 7 发布时似乎是可能的——我只是想知道现在是否有解决方法.如果 isatty()
在子进程中进行重定向.
This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of isatty()
in the child process carries through the redirection.
推荐答案
您将需要复制 处理输出、错误和输入流到系统版本.最简单的方法是使用 IOUtils 来自 Commons IO 包的类.复制方法 看起来正是您所需要的.复制方法调用将需要在单独的线程中.
You will need to copy the Process out, err, and input streams to the System versions. The easiest way to do that is using the IOUtils class from the Commons IO package. The copy method looks to be what you need. The copy method invocations will need to be in separate threads.
基本代码如下:
// Assume you already have a processBuilder all configured and ready to go
final Process process = processBuilder.start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getOutputStream(), System.out);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(process.getErrorStream(), System.err);
} } ).start();
new Thread(new Runnable() {public void run() {
IOUtils.copy(System.in, process.getInputStream());
} } ).start();
这篇关于在 Java 6 中使用继承的 stdin/stdout/stderr 启动进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!