Coffee_Table
Coffee_Table

Reputation: 284

How to open Command Prompt, change directory and execute a command using Java code (Windows)

The title basically says it all. What I've been able to do so far, by searching around on the web, is the following:

Runtime rt = Runtime.getRuntime();

try {
    Process proc = rt.exec("cmd /c start cmd.exe /K \"cd " + locaction);
} 
catch (Exception e) {
    //...
}

where location is the String representation of the directory I'd like to switch to. Not sure if the above is the best way to do that, but either way, how do I then run a certain command from that directory (say, e.g., there's an application there and I want it to run)? Thanks.

Upvotes: 0

Views: 4392

Answers (1)

assylias
assylias

Reputation: 328608

If you just want to run an application with a specific working directory, the easiest way is to use a ProcessBuilder:

ProcessBuilder pb = new ProcessBuilder(executable, arguments, if, any);
pb.directory(theWorkingDirectory);
pb.start();

Upvotes: 3

Related Questions