Java:与命令行应用程序通信

时间:2015-08-26 10:03:11

标签: java macos io terminal communication

我想用Java编写国际象棋GUI。用户可以输入一个移动,然后我希望程序进行移动。因此我将使用UCI(通用国际象棋界面)。 UCI是一个终端/命令行应用程序(我正在使用Mac OS X和终端)来计算某个位置的最佳移动。现在我需要做的是写入并读取此终端应用程序。

例如: 我想要一个特定位置的最佳动作,所以我键入: “go”(计算最佳动作)

假设我得到了这个答案: “e2e4”(意思是将棋子(国际象棋中的棋子)从e2平方移动到e4平方)

现在我需要阅读“e2e4”,然后询问用户他的下一步行动。所以我需要一直循环这些步骤,直到有一个将死: 1.要求搬家 2.计算最佳响应

我已经看到很多其他StackOverflow问题提出了同样的问题:如何运行命令并在命令行/终端中获取其输出。但是所有答案只使用一个命令,例如runtime.exec("ls");但这只是一个命令。我想要的是输入命令,获取响应,执行另一个命令等等,所以基本上我需要与Mac OSX的终端应用程序(交替输入和输出)进行通信。我如何在Java中实现这一目标?

3 个答案:

答案 0 :(得分:1)

您可以执行运行国际象棋程序的命令,然后检查命令的输出以获得最佳移动(使用Process)。

例如:

String move = null;
Process process = Runtime.getRuntime().exec("go");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getOutputStream()));
move = reader.readLine();
// 'move'  now holds a reference to the chess program's output, or null if there was none.

答案 1 :(得分:0)

只需查看Runtime.exec()的返回类型即可。它返回java.lang.Process

它提供了两种输入和输出流方法:getOutputStream()和getInputStream()

您可以读取和写入已打开的Process for ex。使用BufferedReaders / BufferedWriters。

例如:(另见https://stackoverflow.com/a/14745245/2358582

import java.io.*;

public class c {
    public static void main(String[] args) throws Exception{
        Process p = Runtime.getRuntime().exec("cmd");
        BufferedReader inp = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

        //communication
        setUpStreamGobbler(p.getInputStream(), System.out);
        out.write("cmd\n");
        out.flush();
    }

    public static void setUpStreamGobbler(final InputStream is, final PrintStream ps) {
        final InputStreamReader streamReader = new InputStreamReader(is);
        new Thread(new Runnable() {
            public void run() {
                BufferedReader br = new BufferedReader(streamReader);
                String line = null;
                try {
                    while ((line = br.readLine()) != null) {
                        ps.println("process stream: " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

输出:

process stream: Microsoft Windows [Version 6.1.7601]
process stream: Copyright (c) 2009 Microsoft Corporation. Alle Rechte vorbehalte
n.
process stream:
process stream: P:\Java\ExcecuteFile>cmd
process stream: Microsoft Windows [Version 6.1.7601]
process stream: Copyright (c) 2009 Microsoft Corporation. Alle Rechte vorbehalte
n.
process stream:

答案 2 :(得分:0)

我相信这个问题可能对您有所帮助:  I asked something similar, 我希望这会回答你的问题

相关问题