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. Commented Jul 2, 2024 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. Commented Jul 2, 2024 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! Commented Jul 2, 2024 at 20:43
  • @Benna the solution applies as well to this one (using the /k argument). Commented Jul 2, 2024 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. Commented Jul 2, 2024 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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
"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.
Thank you, this worked perfectly and solved all my issues :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.