Any way to get a File object from a JAR

2020-02-14 06:52发布

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?

标签: java file io
1条回答
贪生不怕死
2楼-- · 2020-02-14 07:09

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.

查看更多
登录 后发表回答