To run the commands in a specific directory in Java, you are required to set the working directory or navigate to it through the command you send to cmd.exe. The Runtime.getRuntime().exec() function executes a sequence of commands found in the Command Prompt, navigating to a directory and further executing other commands.
Following is the guide and an altered version of your code to accomplish this:
Major Steps:
1. Open Command Prompt and change (cd) to given directory
Run in batch mode, the commands separated with && to ensure that if the previous command was successful then only the next one will be executed.
End
// Execute several commands in a chain
// "cd" to the desired directory, then execute more commands
String[] commands = { "cmd.exe", "/c", "cd " + newDir + " && dir" };
// Run the command
Process process = rt.exec(commands);
// You can read the output of the process if needed (optional)
process.getInputStream().transferTo(System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CmdRunner cmdRunner = new CmdRunner();
// Change to your desired directory path
cmdRunner.excCommand("C:\\Program Files\\Flowella");
}
}
Explanation
1. cmd.exe /c: Opens the Command Prompt and runs commands until it exits.
2. cd <directory> && dir:
- cd <directory> navigates to the specified directory.
- && dir lists files in the directory. You just replace dir with whatever operation you wish to carry on that directory.
3. Pipeline Output (Optional)
The line process.getInputStream().transferTo(System.out); catches the output of any commands you run and it will print it on to your console.
Running In Sequence
Should you wish to do lots of different operations on in the same console window all at once, you might want to group commands so that you type:
String[] commands = { "cmd.exe", "\\""/c\\"", "cd " + newDir + " && your_command_here && another_command" };