簡體   English   中英

我可以在開始從stdout讀取行之前等待過程完成嗎?

[英]can I wait the process to finish before starting reading lines from stdout?

假設我開始一些過程而沒有閱讀所有內容,

     ProcessBuilder pb = new ProcessBuilder(commands); 

    // startinf the process 
    Process process = pb.start(); 

我可以等到過程完成才能以這種方式讀取行嗎?

     runSafely(() -> process.waitFor());
    // for reading the ouput from stream 
    BufferedReader stdInput = new BufferedReader(new
     InputStreamReader(process.getInputStream())); 
    String s = null; 
    while ((s = stdInput.readLine()) != null) 
    { 
        System.out.println(s); 
    } 

我的問題是我一直在等待。

據我所知,在定義流程流並開始處理它們之前,使用waitFor應該不會有任何問題。 但是,如果您堅持等待,可能還會有其他問題。 您應該仔細檢查您要調用的程序是否在其輸入中沒有期望的內容,而且commands列表已正確組裝,因此該程序由於某種原因不會掛斷。 您也可以嘗試添加超時。 最后,外部程序可能完成得太快-這可能導致waitFor也永遠等待。

無論哪種方式,最好在捕獲要使用的流之后調用waitFor

同樣也不清楚為什么要在lambda表達式中使用waitFor方法,因為該表達式實際上在其內部生成了一個私有類,這看起來很可能引起問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM