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

前端 未结 1 1451
独厮守ぢ
独厮守ぢ 2021-01-14 21:21

I have an EXE file, addOne.exe which continuously gets an integer input from the user on the console (NOT command line paramet

相关标签:
1条回答
  • 2021-01-14 21:55

    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()
    0 讨论(0)
提交回复
热议问题