views:

308

answers:

2

I'm trying to local a properties file programmatically without having to pass it's fullpathname on the commandline to my program. I figure if I can locate the path of the main class, I can stick my properties file in the same directory or a sub-directory.

If that won't work is there some other way I can locate the path of a properties file without passing it in on the commandline.

Thanks

+8  A: 

If the file is expected to be located relative to the main class, you can use Class.getResource() or Class.getResourceAsStream() as follows:

class MainClass {
    public static void main( String[] args ) {
        URL props = MainClass.class.getResource( "foo.properties" );
        // ...
    }
}

These will return a URL or an InputStream, respectively; there's an overload for Properties.load() which accepts an InputStream.

You can specify paths in subdirectories, etc. relative to the class' location, or use the getResource() method on another class to obtain files relative to that location.

If you want to calculate a path relative to the current working directory (which is not necessarily the same as the parent of the main class), then you can use the following to obtain that path:

String cwd = System.getProperty( "user.dir" );

There's a list of available system properties in the documentation for System.getProperties().

Rob
A: 

You can use the ClassLoader to locate the application directory, but as Rob says, it would be better to load the properties file from the classpath directly.

McDowell