Corv1nus
Corv1nus

Reputation: 4625

Any way to get a File object from a JAR

I have a JAR file that contains an API that uses external model files. I would like to include the model files in the JAR itself so it easier to use for other developers. The API will accept a File object only, is there any way to do this? I have already tried the following, and they have failed:

I suppose an option is to use getResourceAsStream and move the files to a permanent location on the HDD but, I do not like this option. There has to be something better, any thoughts?

Upvotes: 3

Views: 1837

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308031

Resources in a .jar file are not files in the sense that the OS can access them directly via normal file access APIs.

And since java.io.File represents exactly that kind of file (i.e. a thing that looks like a file to the OS), it can't be used to refer to anything in a .jar file.

A possible workaround is to extract the resource to a temporary file and refer to that with a File.

Note that generally APIs that try to handle files should be written to handle InputStream/OutputStream as well to allow this kind of operations to suceed.

Upvotes: 9

Related Questions