Start CMD by using ProcessBuilder

34,098

Solution 1

You need to use the start command. Actually, even I don't see a new command prompt popping up, but you can check that a new cmd.exe is definitely started using your task manager.

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start");

Though, the same functionality can be achieved using Runtime.exec(), and this actually pops up a new command prompt.

Runtime.getRuntime().exec("cmd.exe /C start");

Solution 2

To use it with ProcessBuilder you must separate the commands like this:

final List<String> commands = new ArrayList<String>();                

commands.add("cmd.exe");
commands.add("/C");
commands.add("start");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.start();
Share:
34,098
Birdman
Author by

Birdman

Updated on July 09, 2022

Comments

  • Birdman
    Birdman almost 2 years

    I am trying to start the CMD application in windows by using the following code, but it doesn't work as expected. Several examples from different websites shows that "cmd" as an argument in the ProcessBuilder construct should work.

    What do I have to do to make my Java app open the CMD application in windows?

     public class JavaTest
     {
         public static void main(String[] args) 
         {
             ProcessBuilder pb = new ProcessBuilder("cmd");
    
             try 
             {
                 pb.start();
                 System.out.println("cmd started");
             } 
             catch (IOException e) 
             {
                 System.out.println(e.getMessage());
             }  
         }
     }
    

    When I try to use a non-existing application it actually prints out an error, so that means it actually runs "CMD". But the CMD application doesn't pop up as expected?

  • Birdman
    Birdman almost 12 years
    The ProcessBuilder doesn't work as expected (Which I find very, very weird) - But the "exec()" method does the job. Thank you!
  • quest-lion
    quest-lion over 11 years
    String[] cmd = new String[]{"cmd.exe", "/C", "start"}; ProcessBuilder pb = new ProcessBuilder(cmd); Process process = pb.start();
  • john
    john over 9 years
    I don't know what /C mean?,it's not the path of C drive
  • Kazekage Gaara
    Kazekage Gaara over 9 years