Login  Register

Re: get directory for a class instance

Posted by Ben.BigHair on Jul 12, 2007; 6:53pm
URL: http://imagej.273.s1.nabble.com/get-directory-for-a-class-instance-tp3698874p3698876.html

On Jul 12, 2007, at 08:03 AM, Johannes Schindelin wrote:

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

Hi,

Thanks for this neat trick.   In addition to what you demonstrate  
above I can also get the path to the plugin class file itself ala...


import java.io.*;
import java.net.URL;

     URL url = getClass().getResource("myClassName.class");
     File pFile = new File(url.getPath());
     String pPath = pFile.getParent() + File.separator;

I especially like this because I also distribute a macro with the  
plugin, and, to simplify my life, I decided to keep the macro with  
the plugin.   I realize that this is unorthodox but the macro only  
has meaning when called from the plugin.  I need the path to the  
macro for...

        String result = IJ.runMacroFile(stringPathToMacro, argumentString);

Thanks again,
Ben