10

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Birdman
  • 5,244
  • 11
  • 44
  • 65
  • 1
    If you called your auto mechanic and said "my car doesn't work", what would his first question be? If you don't tell us what the error message was, how do you expect to get any help? – Jim Garrison Jun 08 '12 at 18:40
  • 3
    Before jumping up with a fancy comment,try reading what the OP says. _so that means it actually runs "CMD". But the CMD application doesn't pop up as expected?_ – Kazekage Gaara Jun 08 '12 at 18:41

3 Answers3

15

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();
Durgesh Gupta
  • 175
  • 1
  • 6
Guilherme
  • 721
  • 6
  • 13
9

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");
assylias
  • 321,522
  • 82
  • 660
  • 783
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
1

use this command if you are windows

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "ping -n 3 google.com");
Vinay Bairagi
  • 331
  • 1
  • 3
  • 8