Login  Register

Re: get directory for a class instance

Posted by dscho on Jul 12, 2007; 1:03pm
URL: http://imagej.273.s1.nabble.com/get-directory-for-a-class-instance-tp3698874p3698875.html

Hi Ben,

On Thu, 12 Jul 2007, Ben Tupper wrote:

> Is there a means to get the the directory of a plugin from an instance of
> that plugin?  I imagine something terribly easy like...
>
> String thisPluginPath = IJ.getDirectory("thisPluginInstance");
>
> I ask because I have a plugin to distribute that includes a user
> preferences file - the dialog for the plugin requires a lot of user
> input.

Good that you added what you need it for.  I was almost up and hacking a
heuristical thing.

But I guess what you really need is the method getResource() of
java.lang.Class:

        import java.io.InputStream;
        import java.net.URL;

        [...]

                URL url = getClass().getResource("myConfiguration.conf");
                if (url != null) {
                        InputStream input = url.openStream();

                        [read input]

IIRC with this incantation the file "myConfiguration.conf" is expected to
be stored in the same directory as the class.  As far as I know, this also
works when you pack your classes in a jar; in that case, the file
"myConfiguration.conf" has to be in that jar, too.

Hth,
Dscho