views:

81

answers:

3
+2  Q: 

get File from JAR

Hi,

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?

Thanks, Don

+2  A: 

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?

Bozho
that will give me an InputStream, but what I really want is a File
Don
what will you do with that `File`?
Bozho
Pass it to an API that requires a File
Don
well in that case create the `File` at a temporary location
Bozho
+3  A: 

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.

Michael Borgwardt
A: 

A quick look at the link you provided for Resource documentation, says the following:

Throws: IOException if the resource cannot be resolved as absolute file path, 
i.e. if the resource is not available in a file system

Maybe the text file is inside a jar? In that case you will have to use getInputStream() to read its contents.

naikus