0

I'm trying to parse a xml file in a game I'm making with libGDX. I get FileNotFoundException under circumstances below.

In a class extending DefaultHandler, I have this method to parse xml under xml/data.xml. If I place this xml folder outside the src/ directory, it works within Eclipse, but not when I export it because the folder "xml" doesn't get included in jar.

Now when I put it under src folder and specify the path as "src/xml/data.xml", it works, again only within Eclipse.

How could I find the path?

public void loadXML() throws SAXException, IOException, ParserConfigurationException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    parser.parse(Gdx.files.internal("xml/data.xml").path(), this);
}
awonderer
  • 665
  • 9
  • 26

1 Answers1

0

I think Eclipse is packaging the file into the .jar file when its in the src/ directory (See Eclipse: export to .jar AND include resource files (ANT)), so you first you need to switch from Gdx.files.internal to Gdx.files.classpath to look the file in the jar via the classpath.

Note that you should be able to tag the xml/ directory as a "source folder" if you want to leave it at the top-level.

The second issue is that there is no "path" for a file stored inside a .jar. That is there is no String like "/this/is/a/path/to/a/file" that can represent files inside a .jar (so the call to .path() on the File won't return anything useful). You can ask for an InputStream or a Reader of such a file-in-a-jar, though. I think Gdx.files.classpath("xml/data.xml").reader() (or .read(1024)) should work (assuming there is a SAXParser parse method that takes a Reader (or InputStream). If SAXParser requires a String path, you may need a different approach.

Community
  • 1
  • 1
P.T.
  • 24,557
  • 7
  • 64
  • 95
  • I specified the path with `Gdx.files.classpath("xml/data.xml").path()` and added the xml/ as source folder. It works in Eclipse, but not when exported. I get this exception when I run the jar. _java.io.FileNotFoundException:C:\Users\Me\Desktop\xml\data.xml_ – awonderer Mar 06 '13 at 22:18
  • Ah .. I think you're running into the problem where there is no "path" to a file packaged up inside a .jar in the classpath. You need to use a SAXParser API that expects a stream ... See http://stackoverflow.com/questions/793213/getting-the-inputstream-from-a-classpath-resource-xml-file – P.T. Mar 07 '13 at 01:32
  • Thank you! `ClassLoader.class.getResourceAsStream` worked! Could you explain a little more on what was going on? What do you mean by a SAXParser API that expects a stream? – awonderer Mar 07 '13 at 04:56
  • Heh, glad that works. I think I understand what's going on now. (This libgdx classpath/file/internal stuff has always been a bit fuzzy to me.) I've updated my answer to explain more. – P.T. Mar 07 '13 at 06:17