DNL PLAYZ
DNL PLAYZ

Reputation: 1

Is there any way to send a code to a batch file via Java?

I've been trying to run a batch file (run.bat for a minecraft server) via Java console. while i did manage to figure out a way to run the batch script on java, it seems that i cannot send commands from the console. the image below is the problem, typing help will not execute a command, is there a way to this?

I'm not allowed to embed images yet so here:

Here's my code snippet:

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException{
        String line;
        Process p = Runtime.getRuntime().exec("run.bat");
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        input.close();
    }
}

Upvotes: 0

Views: 78

Answers (1)

LPanic
LPanic

Reputation: 82

You need to capture the process’s output in one thread and simultaneously send user input to the process in another.

One approach would be to start the batch with ProcessBuilder, redirect I/O, and use two threads (one reading p.getInputStream() and printing to System.out, the other reading System.in and writing to p.getOutputStream()).

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "run.bat");
pb.redirectErrorStream(true);
Process p = pb.start();

// Thread to read process output
new Thread(() -> {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

// Main thread to send user commands
try (PrintWriter pw = new PrintWriter(p.getOutputStream(), true);
     BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) {
    String command;
    while ((command = userInput.readLine()) != null) {
        pw.println(command);
    }
}

Alternatively, if you only need to send commands programmatically (not interactively), consider enabling RCON in the server properties and sending commands via a Minecraft RCON library.

Upvotes: 0

Related Questions