Accessing XML Resources from a JAR File
Accessing resources from within a JAR file can often be necessary in Java applications. This question addresses specifically the issue of reading an XML file from a JAR located in a separate JAR being executed as a desktop application.
To access the XML file from the JAR, the correct method to use is java.lang.Class.getResourceAsStream(String). Passing the file path as a string argument to this method will provide a stream for the file, which can then be parsed using the desired XML parsing methods.
An example of how to use this method is shown below:
URL url = getClass().getResourceAsStream("/xxx/xxx/xxx/services.xml"); XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler( this ); xr.setErrorHandler( this ); xr.parse( new InputSource( url ));
By utilizing getResourceAsStream instead of getResource and passing the file as a URL argument, the program will be able to successfully read the XML file from within the JAR.
The above is the detailed content of How to Access XML Resources from a JAR File in a Java Desktop Application?. For more information, please follow other related articles on the PHP Chinese website!