My Java application has to work like this:
You should use ExpectJ, a Java implementation of the Unix expect utility.