Example: I want to change directory to : C:/temp/hacking/passsword and execute a command like that : java Helloworld arg1 arg2 How can I do this with java?
Asked
Active
Viewed 1.0k times
-3
-
What do you mean by "change directory"? Does your program keep track of a "current directory"? – Code-Apprentice Oct 10 '16 at 01:08
-
Type `Help` in the command prompt. For each command listed type `help
` (eg `help dir`) or ` – Oct 10 '16 at 01:08/?` (eg `dir /?`). `cd C:\temp\hacking\passsword` then `c:\FolderJavaInstalledIn\java Helloworld Arg1 arg2`. `\` is the path separator in windows. -
A Java program is not a shell. While there's a "current directory" (the value of the `user.dir` system property), you provide the working directory to each process you launch using `Runtime` or `ProcessBuilder`. – Jim Garrison Oct 10 '16 at 01:10
-
I'm writing Java program to execute cmd command to change my current directory to another drive and execute a command .More clear? – JamesCornel Oct 10 '16 at 01:13
1 Answers
3
Try this:
Process pr = builder.start();
String[] commands = {"commands"};
ProcessBuilder builder = new ProcessBuilder(commands);
builder = builder.directory(new File(/one/two/dir));
pr = builder.start();
Or if you prefer this approach:
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Users\\Test\" && dir");
Process pr = builder.start();
There are several other questions similar to this one here on SO, I suggest you also go check them out to get a better idea.

Boris Strandjev
- 46,145
- 15
- 108
- 135

Athamas
- 609
- 5
- 16
-
Actually, you cannot run `cd` as it is a shell builtin, and even if you could, it would apply only to the subprocess. It would not carry over back to the Java program or subsequent subprocesses that you launched. – Jim Garrison Oct 10 '16 at 01:11
-
I do not think running `cd` with `Runtime.exec()` will have any effect on subsequent calls. – Code-Apprentice Oct 10 '16 at 01:12
-