【问题标题】:Chain the output of one process to the input of another process将一个进程的输出链接到另一个进程的输入
【发布时间】:2021-03-28 10:54:45
【问题描述】:

我需要通过阻塞的输入/输出流将数据从一个进程传递到另一个进程。有什么东西可以在 JVM 世界中使用吗?

如何让一个进程的输出成为另一个进程的输入?

【问题讨论】:

    标签: java process io stream


    【解决方案1】:

    您可以从单个线程中使用:

    InputStream input = process.getInputStream();
    OutputStream output = process.getOutputStream();
    
    byte[] buffer = new byte[8192];
    int amountRead;
    while ((amountRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, amountRead);
    }
    

    如果要使用两个线程,可以使用PipedInputStreamPipedOutputStream

    PipedOutputStream producer = new PipedOutputStream();
    PipedInputStream consumer = new PipedInputStream(producer);
    
    // This thread reads the input from one process, and publishes it to another thread
    byte[] buffer = new byte[8192];
    int amountRead;
    while ((amountRead = input.read(buffer)) != -1) {
        producer.write(buffer, 0, amountRead);
    }
    
    // This thread consumes what has been published, and writes it to another process
    byte[] buffer = new byte[8192];
    int amountRead;
    while ((amountRead = consumer.read(buffer)) != -1) {
        output.write(buffer, 0, amountRead);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 2023-01-26
      • 2022-01-15
      • 2010-11-23
      相关资源
      最近更新 更多