There are times when you have to use the exec(…) method of java.lang.Runtime class to launch a program. For example:
public void some_method()...String[] commandArray = new String[1];commandArray[0] = "some_program";java.lang.Runtime rt = Runtime.getRuntime();java.lang.Process p = rt.exec(commandArray);...
The outputs of the program you just launched using java.lang.Runtime.exec(…) are directed to your execution context and not to the system console–in other words, the Process object (referenced by “p”) is receiving the output. Now, you can get a handle on the outputs of your program through:
InputStream stderr = p.getErrorStream( );InputStream stdout = p.getOutputStream( );
Next, you can poll the InputStream objects you created and get the desired output, but if you do this inside the same thread that exec(..)’ed commandArray, you’ll need to block till Process object p terminates, which may not be desirable.
...}//end some_method
To avoid this problem, and let some_method() run the rest of its own code and exit, you can take the polling of the outputs of Process object p on separate threads as follows:
public class SomeClass{...public void some_method()...String[] commandArray = new String[1];commandArray[0] = "some_program";java.lang.Runtime rt = Runtime.getRuntime();java.lang.Process p = rt.exec(commandArray);new OutputPollster(p.getErrorStream()).start();new OutputPollster(p.getOutputStream()").start();...}//end some_methosclass OutputPollster extends java.lang.Thread{private java.io.InputStream m_is;OutputPollster(java.io.InputStream is) {m _is = is;}public void run(){int len;byte buf[] = new byte[128];try{while (-1 != (len = _is.read(buf))){System.out.println(new String(buf));}}catch (java.io.IOException ex){//deal with the exception}}}//end OutputPollster definition }//end SomeClass definition