Reputation: 63
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 am trying to code a java program that can:
Scanner.nextInt()
and input to the EXE as console inputI am able to run the EXE using:
new ProcessBuilder("D:\\pathtofile\\addOne.exe").start();
but I don't know how to send input from the Java program to the EXE and get output from the EXE to the Java program.
Thank you.
Upvotes: 3
Views: 5554
Reputation: 11619
When you start an external program with ProcessBuilder
with ProcessBuilder#start()
, a Process
object will be created for the program and as follows:
Process process = new ProcessBuilder("D:\\pathtofile\\addOne.exe").start();
You can access the input stream and output stream with the process
object:
InputStream processInputStream = process.geInputStream();
OutputSteam processOutputStream = process.getOutputStream();
To write data into the external program, you can instantiate a BufferedWriter
with the processOutputSream
:
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(processOutputStream));
To read data from the external program, you can instantiate a BufferedReader
with the processInputStream
:
BufferedReader reader = new BufferedReader(new InputStreamReader(processInputStream));
Now you have all the components to reach your goal:
Scanner#nextInt()
.writer
reader
System.out.println()
Upvotes: 10