Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open cmd.exe in java

Tags:

java

cmd

I have seen several topics about this but i havent got i to work. All i am trying to do is open cmd.exe from a java program.

notepad.exe opens fine.

The problem is that cmd.exe dosent open, the code compiles fine with no error

here is my code:

public class CMD {

public static void main(String[] args) {

  //Trying some variants how to start. 

  //String cmd = "C:\\WINDOWS\\system32\\cmd.exe";
  //String[] cmd = {"C:\\WINDOWS\\system32\\cmd.exe","start"};

  String[] cmd = {"C:\\WINDOWS\\system32\\cmd.exe","/c","start"};

   // notepad works fine
   //String notepad = "C:\\WINDOWS\\system32\\notepad.exe";


 try {        
    Runtime runtime = Runtime.getRuntime();
    //Process p = runtime.exec(notepad);
    Process p = runtime.exec(cmd);


 }

catch (java.io.IOException exception) {
    System.out.println("Caught IOException: " + exception.getMessage());

    }
}
}
like image 549
Daniel Avatar asked Dec 26 '22 17:12

Daniel


1 Answers

try this..

public static void main(String args[]) {
    try {
        Runtime.getRuntime().exec("cmd.exe /c start");
        System.out.println("ok");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
like image 162
subash Avatar answered Dec 28 '22 07:12

subash