打印命令行执行结果

时间:2013-10-28 15:50:41

标签: java runtime.exec

从java程序执行linux命令行后,我需要在System.out.println中打印错误输出,

所以这是我的代码:

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)
...

2 个答案:

答案 0 :(得分:2)

代码中的这一行正在消耗子进程的错误输出(并将其打印到当前进程错误输出)。

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

所以,你应该已经得到了你想要的效果。

(StreamReaderThread可能正在关闭该流,这就是为什么后来尝试从中读取它失败的原因。)

答案 1 :(得分: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()); 
  }