How do I change the working directory of a program from inside Java? Can I use "user.dir"?

David Rees

The short answer is that you can't.

Note that setting the "user.dir" in Java doesn't change the working directory - it only seems to ;). All it really does is update the path that the methods getAbsolute* and getCanonical* work relative to.

For instance if you start a program in Java in the directory c:dir1 you will get the following:

java.io.File aFile;
aFile = new java.io.File("test.txt");
aFile.getAbsolutePath();		// value is c:	emp	est.txt
aFile.createNewFile();			// creates c"	emp	est.txt
aFile.getAbsolutePath();		// value is c:other	est.txt
aFile = new java.io.File("test2.txt");
aFile.getAbsolutePath();		// value is c:other	est2.txt
aFile.createNewFile();			// creates c:	emp	est.txt

There is a RFE for this in with Sun 4045688.

Generally I would suggest avoiding relative file creations - always use File(X,path). Otherwise a user or other code changing user.dir can break things.