Search code examples
javaprocessbuilder

Input various strings to same process in Java


I am writing a Java program which accesses a compiled C++ program via a ProcessBuilder. The C++ program takes a while to "start up", but once it has done so, it can take in strings of text and get an output (currently being written to a text file) very quickly.

Essentially, is there a way to have a running process "wait" for an input to be given to it, rather than have to enter the input source as it is started? I don't want to have to restart a process every time a user inputs a String, as that will take too long and is unnecessary. At the same time, I want to start the process, have it "ready", and then prompt the user for an input. As soon as the user does so, I want to send that input to the running process, collect the output, and present that. Is this possible to do?

Thanks!


Solution

  • If you want the Java program to "wait" for the C++, you need some way for the C++ program to tell the Java program that it is ready. You could do this by sending a message from the C++ program's output stream to the Java program, and have the Java program wait until it reads something on it's own input stream before it prompts the user for input.

    On the other hand, the only reason for your Java program to wait is cosmetic. If all your communication is happening over streams, the Java program can start sending strings to the C++ at any time, and the C++ will read those strings from its input stream once it finishes starting up. Not having the Java program wait means the time between user input and received output might be longer, but the total time between starting up the C++ program and receiving the output may actually be reduced.