I use Runtime exec() method to create a subprocess in Java. However, since the subprocess is an interactive program, I need to provide input to it as and when required by it. Also I need to show the output of the subprocess. How can I do this in the simplest possible way?
I was using a StreamGobbler to show the program output using process.getInputStream(). I, however, do not know how to identify when the program is waiting for input and when to provide it input using proc.getOutputStream. How can I do this?
You need to copy the input and output between the subprocess’ streams and
Systemstreams (System.in,System.outandSystem.err). This is related to my recent quesion. The best solution I have found so far is:The tricky part here is to extract a channel from
System.in. Without this you will not be able to interrupt the thread that reads input when the subprocess terminates.This approach has a serious drawback: after closing
System.inyou can no longer read from it. The workaround that I’m currently using is to have a single input redirecting thread used for all subprocesses.