2013-10-28 144 views
1

在Java程序中,我需要打印出一個錯誤的System.out.println輸出執行Linux命令行後,打印命令行執行結果

因此,這裏是我的代碼:

try { 
    Process proc = Runtime.getRuntime().exec(xmlcommand, null, new File(servlet.getInitParameter(Constants.WORKING_DIR))); 
    outThread = new StreamReaderThread(proc.getInputStream(), System.out); 
    errThread = new StreamReaderThread(proc.getErrorStream(), System.err); 
    outThread.start(); 
    errThread.start(); 
    proc.waitFor(); 
    //finish reading whatever's left in the buffers 
    outThread.join(); 
    errThread.join(); 

// Read from an input stream 
String line; 
BufferedReader input = new BufferedReader(new InputStreamReader(proc.getErrorStream())); 
    line = input.readLine(); 

    while(line != null) 
    { 
     System.out.println(line); 
     line = input.readLine(); 
    } 
} catch (IOException e) { 
// new Notification(e.getMessage(), Notification.Type.ERROR_MESSAGE).show(ui.getPage().getCurrent()); 
    e.printStackTrace(); 
} catch (InterruptedException e) { 
    new Notification(e.getMessage(), Notification.Type.ERROR_MESSAGE).show(ui.getPage().getCurrent()); 
} 

但我在執行後得到這個錯誤:

java.io.IOException: Stream closed 
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162) 
at java.io.BufferedInputStream.read(BufferedInputStream.java:325) 
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) 
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) 
... 

回答

1

您應該強制執行線程打印錯誤輸出

那麼試試這個之前等待:

//finish reading whatever's left in the buffers 
outThread.join(); 
errThread.join(); 

// Read from an input stream 
String line; 
BufferedReader input = new BufferedReader(new InputStreamReader( proc.getErrorStream())); 
line = input.readLine(); 

while(line != null) 
{ 
    System.out.println(line); 
    line = input.readLine(); 
} 

proc.waitFor(); 

} catch (IOException e) { 
// new Notification(e.getMessage(),  
Notification.Type.ERROR_MESSAGE).show(ui.getPage().getCurrent()); 
e.printStackTrace(); 
} catch (InterruptedException e) { 
    new Notification(e.getMessage(),  
    Notification.Type.ERROR_MESSAGE).show(ui.getPage().getCurrent()); 
    } 
+0

是的,這是解決方案:)謝謝。 –

2

代碼中的這行代碼正在消耗子進程的錯誤輸出(並將其打印到當前進程的錯誤輸出中)。

errThread = new StreamReaderThread(proc.getErrorStream(), System.err); 

所以,你應該已經得到你想要的影響。

(StreamReaderThread大概是關閉那個流,這就是爲什麼你以後嘗試從它讀取失敗)。

+0

如何檢索打印到控制檯的字符串? –

+0

@karouileila - 更改StreamReaderThread中的代碼以保存它生成的內容 – jtahlborn