Home >Java >javaTutorial >Why Does FileReader Fail to Read XML from a Java JAR, and How Can I Fix It?
When accessing resources from within JAR files, developers often encounter difficulties. One such issue arises when attempting to read XML files from a JAR using a FileReader, resulting in a "FileNotFoundException" error.
In this specific case, the developer correctly retrieves the URL to the XML file but encounters an error when passing it to a FileReader. This suggests that the URL retrieval method is functional. However, the issue lies in the subsequent steps:
XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler( this ); xr.setErrorHandler( this ); xr.parse( new InputSource( new FileReader( filename )));
The FileReader requires a file path as its argument, whereas the URL obtained by getClass().getResource() points to a resource within the JAR.
To resolve this problem, use the java.lang.Class.getResourceAsStream(String) method, which returns an InputStream that can be used to read the resource:
URL url = getClass().getResource("/xxx/xxx/xxx/services.xml"); InputStream is = url.openStream();
The InputStream can then be used to initialize the InputSource for the XML parser:
xr.parse( new InputSource( is ));
By utilizing getResourceAsStream, the developer can successfully read XML resources from JAR files, eliminating the "FileNotFoundException" error.
The above is the detailed content of Why Does FileReader Fail to Read XML from a Java JAR, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!