Saturday, April 28, 2012

Setting a path relative to the current class directory


Here are some useful and important Java paths:

package somepaths;

import java.io.File;

class SomeImportantPaths{

    public void listPaths(){

        //Path to current working folder
        String ud = System.getProperty("user.dir");
        System.out.println("Working directory:" + ud);

        //Path to OS user directory
        String uh = System.getProperty("user.home");
        System.out.println("Working directory:" + uh);

        //Path to this class directory
        String cp = new  File(getClass().getProtectionDomain().getCodeSource()
                                  .getLocation().getPath()).getAbsolutePath();
        System.out.println("This class directory is: " + cp);

        //Path to this class parent directory
        String cpp = new File(getClass().getProtectionDomain().getCodeSource()
                                        .getLocation().getPath()).getParent();
        System.out.println("This class directory is: " + cpp);
    }
}

public class Main {

    public static void main(String[] args) {
        SomeImportantPaths sip = new SomeImportantPaths();
        sip.listPaths();
    }
}

No comments:

Post a Comment