Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "cd" command using Java runtime?

I've created a standalone java application in which I'm trying to change the directory using the "cd" command in Ubuntu 10.04 terminal. I've used the following code.

String[] command = new String[]{"cd",path}; Process child = Runtime.getRuntime().exec(command, null); 

But the above code gives the following error

Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory 

Can anyone please tell me how to implement it?

like image 739
Antrromet Avatar asked Feb 03 '11 10:02

Antrromet


People also ask

What is CD command in Java?

Cd command is used to change the directory. when type the cd cmd on terminal it will jump one directory to another directory .

How do you execute a command in Java?

Executing a Command from String Process process = Runtime. getRuntime(). exec("ping www.stackabuse.com"); Running this code will execute the command we've supplied in String format.

How does cd command work?

cd or change directoryThe cd command allows you to move between directories. The cd command takes an argument, usually the name of the folder you want to move to, so the full command is cd your-directory . Now that we moved to your Desktop, you can type ls again, then cd into it.


1 Answers

There is no executable called cd, because it can't be implemented in a separate process.

The problem is that each process has its own current working directory and implementing cd as a separate process would only ever change that processes current working directory.

In a Java program you can't change your current working directory and you shouldn't need to. Simply use absolute file paths.

The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly (ProcessBuilder.directory() and the three-argument Runtime.exec() respectively).

Note: the current working directory can be read from the system property user.dir. You might feel tempted to set that system property. Note that doing so will lead to very bad inconsistencies, because it's not meant to be writable.

like image 185
Joachim Sauer Avatar answered Sep 22 '22 03:09

Joachim Sauer