Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top