java - Process 类的 getOutputStream 方法如何工作?

标签 java processbuilder

我正在研究 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/

相关文章:

java - 单元测试 ConsoleAppender log4j

java - 无法让 Spring 注入(inject)我的依赖项

java - ProcessBuilder (java) 的问题

java - ProcessBuilder 挂起

java - 使用 java.lang.ProcessBuilder 在不同主机上运行 shell 脚本

java - 在 Java 中将输入流重用到进程

java - 如何将 x86 编译的库附加到 android 项目

java - 为 sparc T4 8 核正确调整 G1 GC

java - 如何使用 JNI 将 Java 中的 ArrayList<Integer> 转换为 C++ int 数组?

java - 从可能包含空格的 java 执行命令