Almost every article I read told me that you can’t have chdir in Java. The accepted answer to this question says you can’t do it in Java.
However, here’s some of the stuff I tried:
geo@codebox:~$ java -version java version "1.6.0_14" Java(TM) SE Runtime Environment (build 1.6.0_14-b08) Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode, sharing)
Here’s a test class I’m using:
import java.io.*;
public class Ch {
public static void main(String[] args) {
System.out.println(new File(".").getAbsolutePath());
System.setProperty("user.dir","/media");
System.out.println(new File(".").getAbsolutePath());
}
}
geo@codebox:~$ pwd /home/geo geo@codebox:~$ java Ch /home/geo/. /media/.
Please explain why this worked. Can I use this from now on and expect it to work the same way on all platforms?
Just because
new File(".")gives the desired answer doesn’t mean it’s doing what you want it to.For example, try:
Where does that end up? On my Windows box, even though
new File(".").getAbsolutePath()moves around based onuser.dir,foo.txtis always created in the original working directory. It strikes me that settinguser.dirsuch thatnew File(".")doesn’t refer to the current working directory is just asking for trouble.