【问题标题】:How to reference an xml file from resources? Eclipse如何从资源中引用 xml 文件?蚀
【发布时间】:2015-03-21 01:52:12
【问题描述】:

我正在使用 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);
    }

下图显示了将文件添加到资源文件夹后的项目结构,但是将其添加到资源文件夹会导致找不到文件。

【问题讨论】:

    标签: java xml eclipse resources filepath


    【解决方案1】:

    问题在于 game.xml 在技术上位于“资源”包中。因此使用

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

    应该做的伎俩

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 2011-05-09
      相关资源
      最近更新 更多