0

I currently have some code that executes a task:

this.cmds = new String[] { "cmd.exe", "/c", customCmd };
ProcessBuilder pb = new ProcessBuilder(cmds);

try {
    pb.start();
} catch (IOException e) {
    e.printStackTrace();
}

This works perfectly and does what I expected.

However, I would like to actually display a visible cmd window when running this specific task.

Is this possible?

Thanks for your time,

Benna

6
  • This question is similar to: BAT file: Open new cmd window and execute a command in there. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
    – aled
    Commented Jul 2 at 19:57
  • 3
    That post is relating to opening a windows command line with a BAT file. Not a Java program. When I use the same logic as this post using /k instead of /c nothing changes and the cmd line window is still executing in the background.
    – Benna
    Commented Jul 2 at 20:03
  • This question seems to be the opposite of this one. You're having a problem getting the console window to be visible, while the asker of the other question is having a problem getting the console window NOT to be visible. Perhaps you should swap jobs!
    – k314159
    Commented Jul 2 at 20:43
  • @Benna the solution applies as well to this one (using the /k argument).
    – aled
    Commented Jul 2 at 20:56
  • @aled the OP did say "... /k instead of /c nothing changes..." so they did address your comment and it's not a duplicate.
    – k314159
    Commented Jul 2 at 20:57

1 Answer 1

0

Use this line:

this.cmds = new String[] { "cmd.exe", "/c", "start cmd.exe /k " + customCmd };

The first "cmd.exe", "/c" starts invisible window, but then inside you use command start cmd.exe /k ... to create visible window and it will stay open because of /k.

3
  • Even better would be "start %ComSpec% /D /K " or "start %SystemRoot%\\System32\\cmd.exe /D /K " instead of "start cmd.exe /k " as in this case the first started cmd.exe does not need to search for the second to start cmd.exe file in file system and the second started cmd.exe does not read the AutoRun registry value. "/D" as additional argument (option) for first started cmd.exe before "/c" would be also useful to prevent reading the AutoRun registry value and executing it if really existing.
    – Mofi
    Commented Jul 3 at 9:03
  • "cmd.exe" should be also replaced by System.getenv("ComSpec") for calling the Windows kernel library function CreateProcess with the executable to run with its fully qualified file name.
    – Mofi
    Commented Jul 3 at 10:35
  • Thank you, this worked perfectly and solved all my issues :)
    – Benna
    Commented Jul 3 at 14:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.