java - How to reference an xml file from resources? Eclipse -
i'm parsing in xml file using sax
, need add resource instead of hard coding file path.
i set file path y using string this:
private static final string game_file = "game.xml";
its been suggested use getresourceasstream
i'm not sure how apply solution.
does how reference file resources instead within project?
this how reference xml file adding root of project, bad practice:
public class parser extends defaulthandler{ private static final string game_file = "game.xml"; //you should have boolean switch each xml element, not attribute boolean location = false; boolean description = false; boolean item = false; boolean gamecharacter = false; boolean searchalgorithm = false; //read in xml file game.xml , use current object 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 project structure after adding file resources folder, adding resources folder, causes file not found.
the problem game.xml technically in "resources" packages. using
game_file = "/resources/game.xml" inputsource source = new inputsource(getclass().getresourceasstream(game_file));
should trick
Comments
Post a Comment