如何使用java.lang.Process类为另一个进程提供输入 [英] How to use java.lang.Process class to Provide inputs to another process
问题描述
假设有一个程序从标准输入中获取输入。
Just assume there is a program which takes inputs from the standard input.
例如:
cin>>id;
我想弄清楚的是如何执行流程并为其标准输入提供一些输入。获取流程的输出对我来说不是问题。它工作正常。问题是如何使用 java.lang.Process
类为这些进程提供输入。
What I want to figure out is how to execute the process and give some input to its standard input. Getting the output of the process is not an issue for me. It works properly. The question is how to feed inputs for such processes using java.lang.Process
class.
如果有的话其他第三方图书馆如Apache commons也请提及。
If there are any other third party libraries like Apache commons please mention them also.
提前致谢!
推荐答案
您需要启动一个单独的线程,该线程从一个进程的输出读取并将其作为输入写入另一个进程。
You need to start a separate thread which reads from the output of one process and writes it as input to the other process.
这样的事情应该做:
class DataForwarder extends Thread {
OutputStream out;
InputStream in;
public DataForwarder(InputStream in, OutputStream out) {
this.out = out;
this.in = in;
}
@Override
public void run() {
byte[] buf = new byte[1024];
System.out.println("Hej");
try {
int n;
while (-1 != (n = in.read(buf)))
out.write(buf, 0, n);
out.close();
} catch (IOException e) {
// Handle in some suitable way.
}
}
}
哪个用于 prod>>缺点
如下:
class Test {
public static void main(String[] args) throws IOException {
Process prod = new ProcessBuilder("ls").start();
Process cons = new ProcessBuilder("cat").start();
// Start feeding cons with output from prod.
new DataForwarder(prod.getInputStream(), cons.getOutputStream()).start();
}
}
这篇关于如何使用java.lang.Process类为另一个进程提供输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!