How do I set the current working directory to a particular directory, such that subsequent file opens only need to only use relative file paths?
Created May 4, 2012
John Zukowski I seem to recall a time where setting the user.dir System property did this for you. However, that doesn't seem to work any more (if it ever did). There is no standard way to do this, like a method of the File class or some such. The best you can do is to create a File object for the new "root" directory, then create new File objects passing this as the parameter to it:
File root = new File("/foo/bar"); File real = new File(root, "real");Also, according to David Rees:
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 System.setProperty("user.dir","c:other"); 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.