Search code examples
javauser-inputjava-stream

How do you continuously input from Java program to EXE's console?


I have an EXE file, addOne.exe which continuously gets an integer input from the user on the console (NOT command line parameters) and outputs the integer + 1 onto the console . Sample output is shown below:

1
2

6
7

29
30
...

I have already made the EXE outputs work, that is, Whenever the EXE outputs text to the console, print that text from the Java program. I am trying to:

  • Get user input from the Java program using Scanner.nextInt() and input to the EXE as console input
  • I need to send the input one at a time, which means that simply closing the BufferedWriter stream at the end of the program and inputting the stream into the EXE all at once won't work.

Currently, I have the following code:

Process process = Runtime.getRuntime().exec("D:\\addOne.exe");
...
Scanner keyboard = new Scanner(System.in);
String input = "";
OutputStream stdin = process.getOutputStream();
while (!input.equals("exit")) {
    try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin))) {
        input = keyboard.nextLine();
        writer.write(input);
    } catch (IOException ex) {
        Logger.getLogger(CmdLineTest.class.getName()).log(Level.SEVERE,null,ex);
    }
}

However, whenever I run this code, the first iteration of the while loop (the first time I input something) is able to send the input to the EXE, but after the first iteration, the error java.io.IOException: Stream Closed is given.

How can I continue to get user input from a Scanner.nextInt() inside a while loop

Thank you.


Edit: writer.flush() does not seem to input the user input from the Java program to the EXE.


Edit: see my answer below


Solution

  • It seems that using writer.flush() inputted the stream into the EXE, but the stream required a writer.newLine() before the input was processed by the EXE, as the console requires the enter key to be pressed after the input.

    Here is the working code:

    while (true) {
        try {
            input = keyboard.nextLine();
            writer.write(input);
            System.out.println("IN: "+input);
            writer.newLine();
            writer.flush();
        } catch (IOException ex) {
            Logger.getLogger(CmdLineTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    }