Search code examples
javacmdprocessbuilder

Set the root directory in cmd.exe using java


This is one way to run cmd.exe using java:

String command="cmd /c start cmd.exe";
Process p = Runtime.getRuntime().exec(command);

How to enforce command to run cmd.exe from the root directory C:\ ?


Solution

  • As suggested by others, consider using ProcessBuilder.

    Code:

    ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/C", "start");
    processBuilder.directory(new File("C:\\"));
    try {
        processBuilder.start();
    } catch (IOException e) {
        e.printStackTrace();
    }