Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Nov 20, 1998

Changing the current directory

Question:
How does one change the current working directory of a Java program or a java.lang.Process? The equivalent of the Unix chdir system call seems to be absent.

Answer:
There is no way to change the current working directory of a Java program. If your application needs to keep track of directories, you should start off by using System.getProperty("user.dir") to get the current working directory. Store this in a variable that tracks the current directory, and, as you change the notion of current directory in your program, update the variable. This is usually necessary for Java programs that look for files in relative directories and need to construct absolute paths.

Sometimes Java programs need to spawn other programs using Runtime.exec, but the programs require a different working directory than the current one used by the Java program. To change the initial directory of an execed program, you have to depend on the system shell for your platform (if you have one). For Unix, just calling something like runtime.exec("cd " + newDirectory + "; " + commandName) will do what you need. An alternative is just to write a simple script that sets up the environment for the command and call the script from your Java program.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date