问题
I'd like to parse through XML files with java - ok, easy. It would be REALLY nice if I could use an XML file that I've created within a folder inside my same Eclipse project (let's call it the "resources" folder). Due to issues with version control, multiple development platforms, and general simplicity, it would be VERY, VERY nice to have this capability, rather than accessing the file in the file system.
Is there an easy way to do this, perhaps one that doesn't require downloading/installing additional packages? It's for a school assignment, and the rule is that we can use any library or class that comes with the IDE, but that's it. Using a "nonstandard" library is cheating.
回答1:
You can do this already. (If I understand your question.)
If you have an Eclipse project like so:
Project
src
java.packages
resources
xmlfiles.xml
You can access the xml files like so:
File f = new File("resources/yourXmlFile.xml");
That way you don't have to worry about where the files are exactly on the file system.
Have a look at the StackWrap4J project setup. It is most likely identical to what you want:
回答2:
If you tell Eclipse that the "resources" folder should be considered a source folder (right click on it, then the files from it will be on your classpath when you run your application. You can then access them in your Java program like this:
this.getClass().getResouce("/yourfilename.xml");
You don't have to worry about the working directory - you're just accessing a file on the classpath.
来源:https://stackoverflow.com/questions/3816021/is-there-a-simple-way-to-use-xml-resources-within-a-java-project-in-eclipse