简体   繁体   English

Java:如何使用命令行打开程序并进行交互

[英]Java: How to open a program using the command line and interact

I searched a lot the last hours to open program.exe and interact with it like cmd. 我在最后几个小时搜索了很多,打开program.exe并像cmd一样与它进行交互。 The solutions I found did not work or just worked for opening cmd and running commands like 'dir'. 我发现的解决方案无法正常工作或仅用于打开cmd和运行命令,如'dir'。

I want to open a program (lets say program.exe), entering a command, parsing the output and then entering the next command. 我想打开一个程序(比如program.exe),输入命令,解析输出然后输入下一个命令。 The window of the command line does not have to be open/visible but I need to get the output and enter further commands. 命令行的窗口不必打开/可见,但我需要获取输出并输入更多命令。 How can I do this with Java? 我怎么能用Java做到这一点?

I think what you may be referring to opening another process and running a command-line program from it and passing arguments to this secondary process. 我想你可能指的是打开另一个进程并从中运行命令行程序并将参数传递给这个辅助进程。

If so, what you are looking for is the ProcessBuilder . 如果是这样,您正在寻找的是ProcessBuilder

You can create a Process and obtain an input stream to read from it, or an output stream to write back at it. 您可以创建一个Process并获取一个输入流来从中读取,或者输出一个流来回写它。

You might want to check the following examples: 您可能需要查看以下示例:

You should have a look at Runtime. 你应该看一下Runtime。 It is an object every application has and is there to interact with the environment. 它是每个应用程序都具有的对象,并且与环境进行交互。 http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

You can start a program with "exec" which will return an Process instance. 您可以使用“exec”启动一个程序,该程序将返回一个Process实例。 You can access the output stream by calling "process.getOutputStream();" 您可以通过调用“process.getOutputStream();”来访问输出流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM