Any way to get a File object from a JAR

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

  • Using class.getResourceAsStream (). This will work if the API accepts an InputStream.
  • Parsing the classpath and trying to create from records (JAR will be displayed as app.jar)

I believe the option should use getResourceAsStream and move the files to a permanent location on the hard drive, but I do not like this option. There must be something better, some thoughts?

+3
source share
1 answer

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

And since it java.io.Fileis just such a file (i.e. a thing that looks like a file in the OS), it cannot be used to refer to anything in the .jar file.

A possible workaround is to extract the resource into a temporary file and link to it with File.

Note that usually APIs that attempt to process files should be written to handle InputStream/ OutputStreamin order to allow such operations.

+7
source

Source: https://habr.com/ru/post/1731218/


All Articles