Search code examples
javawindowsprocess

Starting "cmd.exe" in Java and writing to it's standard input


There are a couple of questions similar to this one (here and here for example), but the answers do not work.

Here is my program:

ProcessBuilder pb = new ProcessBuilder("cmd", "/k");
Process p = pb.start();
Writer w = new PrintWriter(p.getOutputStream());
w.write("echo ABCD\n");
w.flush();

This runs, but no console window pops up.

If instead I do this: ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start"); it creates a console window, but it doesn't accept the input ("echo ABCD\n") because the new console window is actually a subprocess of the cmd process I created.

How can I create a cmd process so that the console window will be created immediately (without the "start" command) so that I can send text to it and it will be displayed in the window (as if it came from the console's standard input)?


Solution

  • The executable used for cmd.exe in a console is conhost.exe, so adjust the command to:

    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "conhost.exe");
    

    Working program:

    String cmd = "echo ABCD" + System.lineSeparator();
    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "conhost.exe");
    Process p = pb.start();
    try (OutputStream os = p.getOutputStream()) {
        os.write(cmd.getBytes());
        os.flush();
    }