【问题标题】:Run a sub process, provide Multiple input and output to it correctly in Java运行一个子进程,在 Java 中正确地为其提供多个输入和输出
【发布时间】:2015-12-19 08:42:47
【问题描述】:

我使用 Runtime exec() 方法在 Java 中创建一个子进程。但是,由于子流程是一个交互式程序,我需要在需要时为其提供输入。我还需要显示子流程的输出。我怎样才能以最简单的方式做到这一点?

我正在使用 StreamGobbler 来使用 process.getInputStream() 显示程序输出。但是,我不知道如何识别程序何时等待输入以及何时使用 proc.getOutputStream 为其提供输入。我怎样才能做到这一点?

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.FileChannel;

class StreamCopier implements Runnable {
private InputStream in;
private OutputStream out;

public StreamCopier(InputStream in, OutputStream out) {
    this.in = in;
    this.out = out;
}

public void run() {
    try {
        int n;
        byte[] buffer = new byte[4096];
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
            out.flush();
        }
    }
    catch (IOException e) {
        System.out.println(e);
    }
}
}

class InputCopier implements Runnable {
private FileChannel in;
private OutputStream out;

public InputCopier(FileChannel in, OutputStream out) {
    this.in = in;
    this.out = out;
}

public void run() {
    try {
        int n;
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer.array(), 0, n);
            out.flush();
        }
        out.close();
    }
    catch (AsynchronousCloseException e) {}
    catch (IOException e) {
        System.out.println(e);
    }
}
}

public class Test {
private static FileChannel getChannel(InputStream in)throws NoSuchFieldException, IllegalAccessException
{
        Field f = FilterInputStream.class.getDeclaredField("in");
        f.setAccessible(true);
        while (in instanceof FilterInputStream)
            in = (InputStream)f.get((FilterInputStream)in);
        return ((FileInputStream)in).getChannel();
}

public static void main(String[] args)throws IOException, InterruptedException, NoSuchFieldException, IllegalAccessException
{

Process process = Runtime.getRuntime().exec("java Sum");
    Thread outThread = new Thread(new StreamCopier(process.getInputStream(), System.out));
    outThread.start();

    Thread errThread = new Thread(new StreamCopier(process.getErrorStream(), System.err));
    errThread.start();

    Thread inThread = new Thread(new InputCopier(getChannel(System.in), process.getOutputStream()));
    inThread.start();

    process.waitFor();
    System.in.close();
    outThread.join();
    errThread.join();
    inThread.join();
}
}

以上代码用于执行 Sum.java 文件。

import java.io.*;
class Sum
{
public static void main(String args[])throws IOException
{

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter first number: ");
    int a = Integer.parseInt(br.readLine());
    System.out.print("\nEnter second number: ");
    int b = Integer.parseInt(br.readLine());

    int c=a+b;
    System.out.println("\nThe sum of two number is: "+c);
}
}

Output image after normal compiling and by using Test class

使用Test类程序后输出不同。如何解决这个问题呢?

提前谢谢!!!!

【问题讨论】:

  • 我会尝试逐步调试 Test.java 并查看它在哪里停止/等待或误读。

标签: java


【解决方案1】:

你的错误的原因是在InputCopier的读取算法中:

ByteBuffer buffer = ByteBuffer.allocate(4096);
while ((n = in.read(buffer)) != -1) {
    out.write(buffer.array(), 0, n);

while 指令中,read(buffer) 读取内容并将它们(隐式)存储在 ByteBuffer 的当前写入位置(在末尾)。但在那之后,当您调用buffer.array() 时,您将写入out 整个 后备缓冲区。

尽管如此,我建议您放弃 StreamCopier 并始终使用 InputCopier 将每个流复制到另一个上。

并且还要将线程设置为守护进程,而不是在执行结束时阻塞JVM。

【讨论】:

  • 您提供的解决方案将帮助我完成最后一年的文凭项目。非常感谢。
  • 不客气。我很高兴为您提供帮助...但是一点点赞也不会伤害我... ;-)
【解决方案2】:

我让你的代码使用普通的 InputStream 运行:

class InputCopier implements Runnable {

    private InputStream in;
    private OutputStream out;

    public InputCopier(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

public void run() {
    try {
        int n;
        byte buffer[] = new byte[4096];
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
            out.flush();
        }
        out.close();
    } catch (AsynchronousCloseException e) {
    } catch (IOException e) {
        System.out.println(e);
    }
}

}

【讨论】:

  • 您提供的解决方案将帮助我完成我最后一年的文凭项目。非常感谢。
猜你喜欢
  • 2011-05-15
  • 2022-11-11
  • 2018-09-11
  • 2014-11-10
  • 2015-04-21
  • 2021-10-03
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多