4

Runtime.getRuntime().exec()

The former does not work when I pass it the command "cd filename"
full code;

package com.piomnicron.riles;

import java.io.File;

import javax.swing.JOptionPane;

public class A {
protected static Runtime B = Runtime.getRuntime();

public static void main(String[] args) {
    File E = new File("");
    System.err.println(E.getAbsolutePath());
    try{
        B.exec("cd "+E.getAbsolutePath()+"\\");

    }catch(Throwable e)
    {
        JOptionPane.showMessageDialog(null, "had an oopsie!");
        e.printStackTrace();
    }
}

}

My question happens to be, why does it throw the following IOException:

cannot run program "cd": CreateProcess error = 2, The system could not find the file specified

I tried it without the +"\" first in case anyone thinks that might be the answer,

I have done some Googling, and none of the answers i found answer my question in any way, they all focus on opening a jar, or file, but I just want to know why the cd command doesn't work. I cannot use an absolute path for the cd because that means it will break if someone moves the folder it's contained in.

the error is the B.exec(); part in case you were wondering

Please excuse any grammatic errors, the sun is in my eyes and I can barely see the screen.

PotatoPhil
  • 166
  • 1
  • 9
  • What are you trying to do by running `cd` using `Runtime.getRuntime().exec()`? Are you trying to change the current directory of the Java class you're running (`A`)? – Luke Woodward May 14 '14 at 20:51
  • @LukeWoodward No, I am trying to get the command to run there, I actually _am_ trying to run a jar file, but using `B.exec("java -jar PotatoScript.jar");` [Don't Ask] – PotatoPhil May 14 '14 at 20:52
  • What do you think the result of executing that `cd` would be? Put the command(s) in a `.bat` (or `.cmd`) file and then you could exec that. – Elliott Frisch May 15 '14 at 02:56

1 Answers1

8

You can't (usefully) issue a cd command through Runtime.exec. The cd command, on most OS's, is a built-in command of the shell, not an executable (which is why you get the error you get), and it operates on the runtime environment of the shell. Although you could use Runtime.exec to fire up a shell and execute the cd command within it (for Windows that would be cmd.exe /c "cd path"), it would only change the current directory within the shell, not for the program running.

What you need to do is resolve the directory within your program, using the various features of File, and use that resolved absolute file path for whatever it is that you're trying to use cd for.

If you post a (new) question saying what it is you're trying to achieve by using cd, we can help you achieve that, but using Runtime.exec to issue cd isn't going to be the solution.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875