Accessing XML File within JAR File from a Java Desktop Application
In this scenario, you're attempting to access an XML file within a JAR file from a separate JAR running as a desktop application. While you have successfully obtained the URL to the file, passing it to a FileReader using a String results in a FileNotFoundException.
However, you have been able to read image resources from the same JAR using the URL with an ImageIcon constructor. This indicates that the method you're using to get the URL is correct.
URL url = getClass().getResource("/xxx/xxx/xxx/services.xml"); // ...
The issue arises when attempting to parse the XML file:
XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler( this ); xr.setErrorHandler( this ); xr.parse( new InputSource( new FileReader( filename )));
Solution:
The incorrect method for reading the XML file is using new FileReader( filename ). To rectify this, utilize the java.lang.Class.getResourceAsStream(String) method. It provides an InputStream for the resource specified by the name, allowing you to read the XML file.
URL url = getClass().getResourceAsStream("/xxx/xxx/xxx/services.xml"); // ...
The above is the detailed content of How to Access an XML File Embedded in a JAR from a Java Desktop Application?. For more information, please follow other related articles on the PHP Chinese website!