从Java执行EXE并从EXE获取输入和输出 [英] Executing an EXE from Java and getting input and output from EXE

查看:177
本文介绍了从Java执行EXE并从EXE获取输入和输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 EXE 文件 addOne.exe ,该文件会连续从控制台上的用户获取整数输入(不命令行参数),然后将 integer + 1 输出到控制台上.示例输出如下所示:

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

我正在尝试编写一个可以执行以下操作的Java程序:

I am trying to code a java program that can:

  • 运行 EXE
  • 使用 Scanner.nextInt() Java程序连续获取用户输入,并将其输入到EXE作为控制台输入
  • 只要EXE向控制台输出文本,就从 Java程序
  • 打印该文本
  • Run the EXE
  • Continuously get user input from the Java program using Scanner.nextInt() and input to the EXE as console input
  • Whenever the EXE outputs text to the console, print that text from the Java program

我能够使用以下命令运行EXE:

I am able to run the EXE using:

new ProcessBuilder("D:\\pathtofile\\addOne.exe").start();

但是我不知道如何将Java程序中的输入发送到EXE,以及如何将EXE中的输出发送到Java程序.

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.

谢谢.

推荐答案

当使用 ProcessBuilder#start() ProcessBuilder 启动外部程序时,将为该程序创建Process 对象,如下所示:

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();

您可以使用 process 对象访问输入流和输出流:

You can access the input stream and output stream with the process object:

InputStream processInputStream = process.geInputStream();
OutputSteam processOutputStream = process.getOutputStream();

要将数据写入外部程序,可以使用 processOutputSream 实例化 BufferedWriter :

To write data into the external program, you can instantiate a BufferedWriter with the processOutputSream:

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(processOutputStream));

要从外部程序读取数据,可以使用 processInputStream 实例化 BufferedReader :

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. 使用 Scanner#nextInt()从控制台读取用户输入.
  2. 使用 writer
  3. 将用户输入写入外部程序
  4. 使用 reader
  5. 读取外部程序的数据输出
  6. 最后使用 System.out.println()
  7. 将数据打印到控制台
  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()

这篇关于从Java执行EXE并从EXE获取输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆