Search code examples
javainputoutputminecraft

using java to manipulate a minecraft server input/output


I'm trying to manage my minecraft server through java but even though i can read outputs easily I can't manage to get commands or even text in:

ProcessBuilder builder = new ProcessBuilder(
        "cmd.exe", "/c", "cd C:\\my\\path\\ && java -jar server.jar nogui");
builder.redirectErrorStream(true);
Process p;

p = builder.start();
this.p = p;

BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (loop) {
    line = r.readLine();
    if (line == null) { break; }
    System.out.println(line);
}

This works just fine but when I try to send commands it doesn't work at all:

OutputStream os = BotData.minecraftServer.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
String stop = "stop";
try {
    out.write(stop + "\n");
    out.write("\n");
    out.flush();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I've tried with "Command:>>" + stop + "\n" with or without / before stop etc.

Killing the process, forcibly or not, starting it in a thread I'd then stop...

I can get neither text nor commands to work.


Solution

  • OK found it, it is needed to use write() newline() then flush() to send anything to the console.

    My second problem was a dead reference to my process.

    destroying the process doesn't work, but the stop command does.

    using / is useless, \n doesn't replace newline()