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

Execute multiple commands in command line using Java

我正在 Java 研究国际象棋程序。为了计算最佳着法(当一个人与计算机对弈时),我使用了 UCI(通用国际象棋界面)。那是一个终端应用程序(我正在使用 Mac OS X)。使用 Java 我想执行一些命令以获得最佳着法。这就是我到目前为止所拥有的:

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

数组中的第一个命令调用终端应用程序。第二个和第三个都是应用内命令。现在我有一个问题。只执行前两个命令,它们的结果打印在控制台中,第三个命令被忽略。我做错什么了吗?请告诉我如何同时执行第三个(或更多、第四个、第五个等)命令。

您不能使用 Runtime.getRuntime().exec() 在另一个程序中执行命令。 您传递给 exec 方法的数组将数组的第一个元素作为命令,将其他元素作为命令的参数。

来自 public Process exec(String[] cmdarray) throws IOException

的 javadoc

Parameters: cmdarray - array containing the command to call and its arguments.

您必须通过调用 Runtime.getRuntime().exec()

来执行主命令

然后您必须 write/read 使用调用 Runtime.getRuntime().exec()

返回的 Process 的 inputstream/outputstream 命令/答案

要检索进程的输入流和输出流,请对进程对象使用 getInputStream()getOutputStream() 方法