Home > Java > javaTutorial > How to Access an XML File Embedded in a JAR from a Java Desktop Application?

How to Access an XML File Embedded in a JAR from a Java Desktop Application?

Barbara Streisand
Release: 2024-12-06 21:12:20
Original
361 people have browsed it

How to Access an XML File Embedded in a JAR from a Java Desktop Application?

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");
// ...
Copy after login

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 )));
Copy after login

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");
// ...
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template