views:

8724

answers:

5

I'm trying to access an XML file within a jar file, from a separate jar that's running as a desktop application. I can get the URL to the file I need, but when I pass that to a FileReader (as a String) I get a FileNotFoundException saying "The file name, directory name, or volume label syntax is incorrect."

As a point of reference, I have no trouble reading image resources from the same jar, passing the URL to an ImageIcon constructor. This seems to indicate that the method I'm using to get the URL is correct.

URL url = getClass().getResource("/xxx/xxx/xxx/services.xml");
ServicesLoader jsl = new ServicesLoader( url.toString() );

Inside the ServicesLoader class I have

XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler( this );
xr.setErrorHandler( this );
xr.parse( new InputSource( new FileReader( filename )));

What's wrong with using this technique to read the XML file?

+2  A: 

You don't say if this is a desktop or web app. I would use the getResourceAsStream() method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.

duffymo
It's a desktop application. I'll edit the question.
Bill the Lizard
A: 

Outside of your technique, why not use the standard Java JarFile class to get the references you want? From there most of your problems should go away.

GaryF
+8  A: 

Looks like you want to use java.lang.Class.getResourceAsStream(String), see

http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)

iny
+1  A: 

It looks as if you are using the URL.toString result as the argument to the FileReader constructor. URL.toString is a bit broken, and instead you should generally use url.toURI().toString(). In any case, the string is not a file path.

Instead, you should either:

  • Pass the URL to ServicesLoader and let it call openStream or similar.
  • Use Class.getResourceAsStream and just pass the stream over, possibly inside an InputSource. (Remember to check for nulls as the API is a bit messy.)
Tom Hawtin - tackline
+1  A: 

The problem was that I was going a step too far in calling the parse method of XMLReader. The parse method accepts an InputSource, so there was no reason to even use a FileReader. Changing the last line of the code above to

xr.parse( new InputSource( filename ));

works just fine.

Bill the Lizard