0

I'm using QDox to parse java sources. I have a problem with this interface:

import test.Word;

public interface Spellable {
    /**
    * Checks the spell of the word in a given language
    */
    public boolean checkSpell (Word word);  
}

At the moment of parsing the Word type I need to know where the path in the filesystem is. So, is there any way to know that?, maybe using the classpath?

Robert Scholte
  • 11,889
  • 2
  • 35
  • 44
Federico Lenzi
  • 1,632
  • 4
  • 18
  • 34
  • 1
    Do you want the current directory, or the package of the class? The file system location would depend on if it is in a jar file and where your classpath is pointed at. – Mike Miller Nov 12 '10 at 16:37
  • I want the location in the filesystem, the class Word is not in a jar. I don't know how to use the classpath to get it. – Federico Lenzi Nov 12 '10 at 16:39

1 Answers1

0

I don't think it's possible to do this in a nice, 100%-definitely-compatible way. Java actually tries to abstract you away from the filesystem a little bit through the classpath mechanism.

Nevertheless, you can usually get the file path via the classloader. First step is to get a reference to a classloader that can find whatever resource you're interested in (usually the classloader for any of your own classes will work fine; if you have a more complex scenario you should hopefully know which classloader to use).

Then you can ask the classloader for the location of a given resource as a URL, for example:

final ClassLoader loader = getClass().getClassLoader();
final URL resourceLocation = loader.getResource("com/mycomp/coolapp/checkthis.doc");

Now if you're lucky, the URL will use the file:/ protocol, and will describe a location on your local filesystem. If so, you can extract this path and use it as the filesystem location of whatever classpath resource you just looked up. If it's not a file:/ resource, the class may not even exist on your local machine (e.g. it's being loaded remotely via RMI) so you're out of luck in any case.

If this sounds complicated - perhaps you can pass in the working directory as a system property from your Java startup script (e.g. java ... -Dworking.dir=$(pwd)).

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • the second line that you wrote is retuning null, how can I do to add something to the classpath?, in this case Do I have to add the test folder to it? – Federico Lenzi Nov 12 '10 at 16:52
  • @Federico, You need to add the parent folder of the test folder to the classpath. – rsp Nov 12 '10 at 17:53