是否可以將由ProcessBuilder創建的一個進程的輸出傳遞給由另一個ProcessBuilder創建的另一個進程?例如,如果我試圖執行此shell命令:將ProcessBuilder的輸出管道輸出到另一個ProcessBuilder
ls | grep build.xml
我應該如何使用ProcessBuilder執行此操作?
爲@erdinc建議,我嘗試這樣做:
Process process = Runtime.getRuntime().exec("ls");
InputStream is = process.getInputStream();
byte[] buf = new byte[1000];
is.read(buf);
String parameter = new String(buf);
System.out.println("grep build " + parameter);
Process proc2 = Runtime.getRuntime().exec("grep build " + parameter);
InputStream is2 = proc2.getInputStream();
byte[] buf2 = new byte[1000];
is2.read(buf2);
String result = new String(buf2);
System.out.println("proc2 result: " + result);
,但它會產生不同的結果進行比較時,我直接在shell中運行的腳本。我在哪裏做錯了?
解決:請參考菲利普·溫德勒溶液
您的解決方案可行!謝謝菲利普:我實際上會使用這個代碼來調用幾個外部應用程序,如chasen和moses(機器翻譯工具)。 ls | grep的例子只是爲了簡化問題,但感謝您的建議:D我會標記問題解決並upvote您的解決方案。 – ndriks 2012-01-08 12:00:58