Squidiemeister Squidiemeister - 1 year ago 66
Java Question

Executing an EXE from Java and getting input and output from EXE

I have an EXE file,

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:




I am trying to code a java program that can:

  • Run the EXE

  • Continuously get user input from the Java program using
    and input to the EXE as console input

  • Whenever the EXE outputs text to the console, print that text from the Java program

I 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.

Answer Source

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:

  1. Read the user input from console with Scanner#nextInt().
  2. Write the user input to the external program with writer
  3. Read the data output from the external program with reader
  4. Finally print the data to the console with System.out.println()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download