如何从资源中引用 xml 文件?蚀

How to reference an xml file from resources? Eclipse

我正在使用 SAX 在 xml 文件中进行解析,需要将其添加为资源而不是对文件路径进行硬编码。

我使用这样的字符串设置文件路径 y:

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

有人建议使用 getResourceAsStream,但我不确定如何将其应用于我的解决方案。

有人知道如何从资源而不是项目中引用文件吗?

这就是我通过将 xml 文件添加到项目的根目录来引用它的方式,这是一种不好的做法:

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);
    }

下图是将文件添加到resources文件夹后的项目结构,但是添加到resources文件夹后,导致文件找不到。

问题是 game.xml 在技术上是在 "resources" 包中。因此使用

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

应该可以解决问题