Brian Var
Brian Var

Reputation: 6227

How to reference an xml file from resources? Eclipse

I'm parsing in an xml file using SAX and need to add it as a resource instead of hard coding the file path.

I set up the file path y using a string like this:

private static final String GAME_FILE = "game.xml";

Its been suggested to use getResourceAsStream but I'm not sure how to apply that to my solution.

Does anyone how the reference the file from resources instead within the project?

This is how I reference the xml file by just adding it to the root of the project, which is bad practice:

public class Parser extends DefaultHandler{
    private static final String GAME_FILE = "game.xml";

    //You should have a boolean switch for each XML element, but not attribute
    boolean location = false;
    boolean description = false;
    boolean item = false;
    boolean gameCharacter = false;
    boolean searchAlgorithm = false;

    //Read in the XML file game.xml and use the current object as the SAX event handler
    public void parse() throws ParserConfigurationException, SAXException, IOException{
        XMLReader xmlReader = null;
        SAXParserFactory spfactory = SAXParserFactory.newInstance();
        spfactory.setValidating(false);
        SAXParser saxParser = spfactory.newSAXParser();
        xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(this);
        InputSource source = new InputSource(GAME_FILE);
        xmlReader.parse(source);
        xmlReader.setErrorHandler(this);
    }

Below shows the project structure after adding the file to a resources folder, but adding it to the resources folder, causes the file to not be found.

resources location

Upvotes: 0

Views: 3886

Answers (1)

Ueli Hofstetter
Ueli Hofstetter

Reputation: 2524

The problem is that game.xml is technically in the "resources" packages. Thus using

GAME_FILE = "/resources/game.xml"
InputSource source = new InputSource(getClass().getResourceAsStream(GAME_FILE)); 

should do the trick

Upvotes: 1

Related Questions