2

I'm working on a chess program in Java. To calculate the best move (when a person plays against the computer) I use a UCI (universal chess interface). That's a Terminal application (I'm using Mac OS X). With Java I want to execute some commands to get the best move. 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.

  • Is it always the third command? Have you tried other commands? Maybe have a look at [this](http://stackoverflow.com/a/5437863/1638708), don't know if it helps – User42 Aug 26 '15 at 11:51
  • As an aside, if you are using this approach it is worth reading the following in case you find yourself getting hard to track bugs: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html – Mick Sep 03 '15 at 13:52

1 Answers1

1

You can't use Runtime.getRuntime().exec() to execute commands inside another program. 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.

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

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

You have to execute the main command with a call to 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()

To retrieve inputstream and outputstream of a process use the getInputStream() and getOutputStream() methods on the process object

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56