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:
Scanner.nextInt()
and input to the EXE as console inputCurrently, 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
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);
}
}