Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a resource file from a Java jar file?

I'm trying to access an XML file within a jar file, from a separate jar that's running as a desktop application. I can get the URL to the file I need, but when I pass that to a FileReader (as a String) I get a FileNotFoundException saying "The file name, directory name, or volume label syntax is incorrect."

As a point of reference, I have no trouble reading image resources from the same jar, passing the URL to an ImageIcon constructor. This seems to indicate that the method I'm using to get the URL is correct.

URL url = getClass().getResource("/xxx/xxx/xxx/services.xml"); ServicesLoader jsl = new ServicesLoader( url.toString() ); 

Inside the ServicesLoader class I have

XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler( this ); xr.setErrorHandler( this ); xr.parse( new InputSource( new FileReader( filename ))); 

What's wrong with using this technique to read the XML file?

like image 965
Bill the Lizard Avatar asked Dec 31 '08 15:12

Bill the Lizard


People also ask

How do I read a resource file?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().

Can you get source code from a JAR file?

Hi, Jar files are archive files that contains of a lot of different java classes (files). You can use winzip/winrar to open the jar files and you can see those java classes in jar files. Typically you can use a Java decompiler to decompile the class file and look into the source code.

How do I read a file from src main resources?

Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.


2 Answers

Looks like you want to use java.lang.Class.getResourceAsStream(String), see

https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-

like image 123
iny Avatar answered Sep 29 '22 06:09

iny


You don't say if this is a desktop or web app. I would use the getResourceAsStream() method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.

like image 45
duffymo Avatar answered Sep 29 '22 05:09

duffymo