2013-12-10 33 views
1

運行下面的程序:的ProcessBuilder - 掛在的readLine()方法

ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-Command", "dir"); 
    Process p = pb.start(); 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
    String line; 
    while((line = bufferedReader.readLine()) != null){ 
     System.out.println(line); 
    } 

    System.out.println("Exit"); 

永遠不會到達 「退出」 的println - 只是無限地掛在readLine()方法。我知道這是(最有可能)是由於PowerShell在最後一行中不輸出\nreadLine不確定是否已達到末端。有沒有辦法解決這個問題並正確地讀取輸入流? BTW。上的ProcessBuilder inheritIO方法導致同樣的問題...

UPDATE

此:

ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-Command", "dir"); 
     pb.redirectErrorStream(true); 
     Process p = pb.start(); 
//  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
//  String line; 
//  while((line = bufferedReader.readLine()) != null){ 
//   System.out.println(line); 
//  } 
    p.waitFor(); 
    System.out.println("Exit"); 

還掛無限......

回答

1

PowerShell是不是結束。我可能會使用Java來列出一個目錄,但這應該適用於您的示例。

ProcessBuilder pb = new ProcessBuilder("dir"); 
+0

所以我需要在最後提供'exit'這樣的東西? – Bober02

+0

我想你可以關閉標準輸出(來自PowerShell)。 –

0

不知道是什麼問題。我試着用你的代碼創建一個新項目(在幾個try-catch和print語句中添加),它對我很有用。這是我用過的;

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 


public class temp { 

    public static void main(String[] args) { 
     ProcessBuilder pb = new ProcessBuilder("powershell.exe", "-Command", "dir"); 
     Process p; 
     try { 
      p = pb.start(); 
     } catch (IOException e) { 
      System.out.println("Failed to start powershell"); 
      return; 
     } 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String line; 
     System.out.println("Begin!"); 
     try { 
      while((line = bufferedReader.readLine()) != null){ 
       System.out.println("reading..."); 
       System.out.println(line); 
      } 
     } catch (IOException e) { 
      System.out.println("Failed to read line"); 
      return; 
     } 

     System.out.println("Exit"); 

    } 

} 

這裏是導致控制檯輸出,

Begin! reading... 

reading... 

reading... 
    Directory: C:\Users\AbrahamV\workspace\201_stackoverflow reading... 

reading... 

reading... Mode    LastWriteTime  Length Name   reading... 
----    -------------  ------ ----                  reading... d----  12/10/2013 9:29 PM   bin   reading... d----  12/10/2013 9:27 PM   src   reading... 
-a---  12/10/2013 9:27 PM  232 .classpath                 reading... 
-a---  12/10/2013 9:27 PM  393 .project                 reading... 

reading... 

Exit 

輸出是不是瞬間。花了一些時間纔打印出來。

相關問題