2013-10-28 146 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