Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get File from JAR

I'm using Spring's Resource abstraction to work with resources (files) in the filesystem. One of the resources is a file inside a JAR file. According to the following code, it appears the reference is valid

ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

// The path to the resource from the root of the JAR file
Resource fileInJar = resourcePatternResolver.getResources("/META-INF/foo/file.txt");

templateResource.exists(); // returns true
templateResource.isReadable();  // returns true

At this point, all is well, but then when I try to convert the Resource to a File

templateResource.getFile();

I get the exception

java.io.FileNotFoundException: class path resource [META-INF/foo/file.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/m2repo/uic-3.2.6-0.jar!/META-INF/foo/file.txt        
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:198)
at org.springframework.core.io.ClassPathResource.getFile(ClassPathResource.java:174)

What is the correct way to get a File reference to a Resource that exists inside a JAR file?

like image 434
Dónal Avatar asked Aug 10 '10 08:08

Dónal


People also ask

Can we extract files from jar?

The jar-file argument is the filename (or path and filename) of the JAR file from which to extract files. archived-file(s) is an optional argument consisting of a space-separated list of the files to be extracted from the archive. If this argument is not present, the Jar tool will extract all the files in the archive.

Can I get Java files from jar?

You can always extract the source files (Java files) of a jar file into a zip. location on your system. Drag and drop the jar for which you want the sources on the JAD. 3 JAD UI will open with all the package structure in a tree format.


2 Answers

What is the correct way to get a File reference to a Resource that exists inside a JAR file?

The correct way is not doing that at all because it's impossible. A File represents an actual file on a file system, which a JAR entry is not, unless you have a special file system for that.

If you just need the data, use getInputStream(). If you have to satisfy an API that demands a File object, then I'm afraid the only thing you can do is to create a temp file and copy the data from the input stream to it.

like image 108
Michael Borgwardt Avatar answered Oct 21 '22 10:10

Michael Borgwardt


If you want to read it, just call resource.getInputStream()

The exception message is pretty clear - the file does not reside on the file-system, so you can't have a File instance. Besides - what will do do with that File, apart from reading its content?

like image 31
Bozho Avatar answered Oct 21 '22 09:10

Bozho