Question

After executing a linux command line from a java program i need to print error output in a System.out.println,

So here's my code :

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());
}

but i'm getting this error after execution :

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)
...
Was it helpful?

Solution 2

You should force the execution thread to wait before printing the error output

So Try this :

//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()); 
  }

OTHER TIPS

this line in your code is consuming the sub-process's error output (and printing it to the current processes error output).

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

so, you should already be getting the affect that you want.

(The StreamReaderThread is presumably closing that stream, which is why your later attempt to read from it fails).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top