简体   繁体   English

如何从资源引用xml文件? 日食

[英]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. 我正在使用SAX解析xml文件,需要将其添加为资源,而不是对文件路径进行硬编码。

I set up the file path y using a string like this: 我使用如下字符串设置文件路径y:

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. 建议使用getResourceAsStream但是我不确定如何将其应用于我的解决方案。

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: 这是通过仅将XML文件添加到项目的根目录来引用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);
    }

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. 下面显示了在将文件添加到资源文件夹后将项目添加到资源文件夹后导致找不到文件的项目结构。

资源位置

The problem is that game.xml is technically in the "resources" packages. 问题在于game.xml从技术上讲是在“资源”包中。 Thus using 因此使用

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

should do the trick 应该可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM