Search code examples
javacommand-promptprocessbuilder

Accessing command prompt (windows) via java


Can I use ProcessBuilder or something else within the java libraries to access the command prompt in windows and execute commands? I know you can with terminal on mac and I made this:

ProcessBuilder pb = new ProcessBuilder(
      "bash",
      "-c",
      "cd " + System.getProperty("user.dir") + ";" + "someCommandInThatDirectory"
      );

Process p = pb.start();

To execute some command in some directory, is their a similar thing to do via command prompt in windows?

I have this to check the os

String os = System.getProperty("os.name");
  if (os == "Mac OS X") {
    //do the mac thing
    }
  else if (os == "Windows XP" /*blah blah rest of windows types*/) {
    //do the windows one
    }

Solution

  • You can use Runtime.getRuntime().exec:

    String command = "cmd /c start cmd.exe ...your other commands";
    try {
        Process process = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
        e.printStackTrace();
    }