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?
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
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.