[英]Piping a string into Java Runtime.exec() as input
我有一個字符串,我需要管道到外部程序,然后讀回輸出。 我理解如何讀回輸出,但如何將此字符串作為輸入管道? 謝謝!
它是這樣的(未編譯和未經測試)
Process p = Runtime . getRuntime ( ) . exec ( ... ) ;
Writer w = new java . io . OutputStreamWriter ( p . getOutputStream ( ) ) ;
w . append ( yourString ) ;
w. flush ( ) ;
// read the input back
小心你不要造成僵局。 如果進程正在寫入您沒有讀取的數據,同時您正在編寫不讀取的數據,那么在同一個線程中讀取/寫入進程可能會有問題。
我傾向於使用一個小圖案線來讓io進入不同的線程:
import java.io.InputStream;
import java.io.OutputStream;
public final class Pipe implements Runnable {
private final InputStream in;
private final OutputStream out;
public Pipe(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public static void pipe(Process process) {
pipe(process.getInputStream(), System.out);
pipe(process.getErrorStream(), System.err);
pipe(System.in, process.getOutputStream());
}
public static void pipe(InputStream in, OutputStream out) {
final Thread thread = new Thread(new Pipe(in, out));
thread.setDaemon(true);
thread.start();
}
public void run() {
try {
int i = -1;
byte[] buf = new byte[1024];
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
這可能適用於您想要做的事情,也可能不適用 - 也許您處理的是已建立的輸入集合,保證在某些預期輸出后顯示(反之亦然,或者幾次迭代)。 即一些同步塊和步驟類型的交互。
但如果你只是“觀察”可能出現的東西,那么這是一個正確方向的良好開端。 您將傳入一些不同的流並使用一些java.util.concurrent'await(long,TimeUnit)'類型代碼來等待響應。 Java IO基本上永遠阻塞在read()操作上,因此如果您沒有從外部進程獲得預期的響應,那么將您自己與這些線程分開將允許您在一定時間后放棄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.