我正在研究 ProcessBuilder class ,其中表示每个流程构建器管理的流程属性之一如下:
a source of standard input. By default, the subprocess reads input from a pipe. Java code can access this pipe via the output stream returned by Process.getOutputStream(). However, standard input may be redirected to another source using redirectInput. In this case, Process.getOutputStream() will return a null output stream, for which:
- the write methods always throw IOException
- the close method does nothing
然后我查找了名为 getOutputStream 的 API 函数,但是它仍然没有点击 m。
我不明白他们这句话的意思:
Output to the stream is piped into the standard input of the process represented by this Process object.
只是寻找有关其工作原理的说明或可能的示例代码。谢谢
最佳答案
这是一个简单的示例代码。
public class ParentProcess {
public static void main(String[] arags) throws IOException, InterruptedException {
Process p = new ProcessBuilder(
"java", "-cp", "bin", "stackoverflow.ChildProcess").start();
// receive from child
new Thread(() -> {
try {
int c;
while ((c = p.getInputStream().read()) != -1)
System.out.write((byte)c);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
// send to child
try (Writer w = new OutputStreamWriter(p.getOutputStream(), "UTF-8")) {
w.write("send to child\n");
}
System.out.println("rc=" + p.waitFor());
}
}
class ChildProcess {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// receive from parent and send to parent
System.out.println("child recevied: " + s.nextLine());
}
}
结果是:
child recevied: send to child
rc=0
关于java - Process 类的 getOutputStream 方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700885/