简体   繁体   English

使用Java在命令行中执行多个命令

[英]Execute multiple commands in command line using Java

I'm working on a chess program in Java. 我正在用Java开发国际象棋程序。 To calculate the best move (when a person plays against the computer) I use a UCI (universal chess interface). 为了计算最佳移动(当有人与计算机对战时),我使用UCI(通用国际象棋界面)。 That's a Terminal application (I'm using Mac OS X). 那是一个终端应用程序(我正在使用Mac OS X)。 With Java I want to execute some commands to get the best move. 使用Java,我想执行一些命令以取得最佳效果。 That's what I have up to now: 那就是我到目前为止

String[] commands = {"/Users/dejoridavid/Desktop/stockfish-6-64", "isready", "uci"};
Process process = null;
try {
    process = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
    e.printStackTrace();
}

BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));

// read the output from the command
String s;
try {
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
} catch (IOException e) {
    e.printStackTrace();
}

The first command in the array calls the terminal application. 数组中的第一个命令调用终端应用程序。 The second and third one are both in-app-commands. 第二个和第三个都是应用程序内命令。 Now I have one problem. 现在我有一个问题。 Only the first two commands are executed, their result is printed in the console, the third command is ignored. 仅执行前两个命令,其结果将打印在控制台中,第三个命令将被忽略。 Did I do something wrong? 我做错什么了吗? Please tell me how to also execute the third (or more, 4th, 5th, etc) command. 请告诉我如何也执行第三(或更多,第四,第五等)命令。

You can't use Runtime.getRuntime().exec() to execute commands inside another program. 您不能使用Runtime.getRuntime().exec()在另一个程序中执行命令。 The array you pass to the exec method take the first element of the array as the command and the others as parameters for the command. 传递给exec方法的数组将数组的第一个元素作为命令,将其他元素作为命令的参数。

From javadoc of public Process exec(String[] cmdarray) throws IOException 从公共Process exec(String[] cmdarray) throws IOException javadoc Process exec(String[] cmdarray) throws IOException

Parameters: cmdarray - array containing the command to call and its arguments. 参数:cmdarray-包含要调用的命令及其参数的数组

You have to execute the main command with a call to Runtime.getRuntime().exec() 您必须通过调用Runtime.getRuntime().exec()执行主命令

Then you have to write/read the commands /answers using the inputstream/outputstream of the Process returned by the call to Runtime.getRuntime().exec() 然后,您必须使用对Runtime.getRuntime().exec()的调用返回的Process输入流/输出流来编写/读取命令/答案Runtime.getRuntime().exec()

To retrieve inputstream and outputstream of a process use the getInputStream() and getOutputStream() methods on the process object 要检索流程的输入流和输出流,请在流程对象上使用getInputStream()getOutputStream()方法

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

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