繁体   English   中英

使用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方法的数组将数组的第一个元素作为命令,将其他元素作为命令的参数。

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

参数:cmdarray-包含要调用的命令及其参数的数组

您必须通过调用Runtime.getRuntime().exec()执行主命令

然后,您必须使用对Runtime.getRuntime().exec()的调用返回的Process输入流/输出流来编写/读取命令/答案Runtime.getRuntime().exec()

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

暂无
暂无

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

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