Any way to get a File object from a JAR

file, io, java

Solution

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.

Problem

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: - Using class.getResourceAsStream(). This would work if the API accepted an InputStream. - Parsing the classpath and trying to build from the entries (the JAR will show as app.jar) 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?

Original source