Remixt
Remixt

Reputation: 597

How can I change the cmd working directory from java?

I'm trying to execute a bat file(from within java) that isn't in the default working directory. I tried the code below but it doesn't seem to work with the "CD" command.

    String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {

        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

}

///////////////////////////////////////////////////////// Here is the code that is supposed to execute the command ////////////////////////////////////////////////////////

    String command = "cd C:\usmt" ;

    //in windows
    //String command = "ping -n 3 " + domainName;

    String output = obj.executeCommand(command);

    System.out.println(output);

Upvotes: 1

Views: 422

Answers (2)

Petro
Petro

Reputation: 3652

Try something like this:

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\myfile.txt");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
    }
}

If you're trying to perform this without a cd, use:

 ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "C:\\Program Files\\myfile.txt");

Upvotes: 1

Χpẘ
Χpẘ

Reputation: 3451

It depends on what you are trying to accomplish. If you want your java program to have a new CWD, then you'll do one thing. If you want to execute a sub-shell (as the other answer assumes), you can do what that answer says.

I'll assume the former. Every windows process has its own CWD. If you spawn a process that changes its CWD, then the spawning process is unaffected.

The Win32 API to change a process' CWD is SetCurrentDirectory. What little I knew about Java, I've long since forgotten. Maybe java has an API that invokes SetCurrentDirectory within its implementation. Or if java has something like .NETs P/Invoke (a way for managed code to call an unmanaged API), you could use that.

Upvotes: 0

Related Questions