-3

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?

JamesCornel
  • 35
  • 1
  • 8
  • 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 ` /?` (eg `dir /?`). `cd C:\temp\hacking\passsword` then `c:\FolderJavaInstalledIn\java Helloworld Arg1 arg2`. `\` is the path separator in windows. –  Oct 10 '16 at 01:08
  • 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 Answers1

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
  • 43,262
  • 13
  • 98
  • 123
Athamas
  • 599
  • 4
  • 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
  • Sorry, I got a little confused, the ProcessBuilder will work. – Athamas Oct 10 '16 at 01:15