Is there a way in Java to construct a File instance on a resource retrieved from a jar through the classloader?
My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I’m looking for a consistent way of
a) loading these files as a stream
b) listing the files in the user-defined directory or the directory in the jar respectively
Edit: Apparently, the ideal approach would be to stay away from java.io.File altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?
ClassLoader.getResourceAsStreamandClass.getResourceAsStreamare definitely the way to go for loading the resource data. However, I don’t believe there’s any way of ‘listing’ the contents of an element of the classpath.In some cases this may be simply impossible – for instance, a
ClassLoadercould generate data on the fly, based on what resource name it’s asked for. If you look at theClassLoaderAPI (which is basically what the classpath mechanism works through) you’ll see there isn’t anything to do what you want.If you know you’ve actually got a jar file, you could load that with
ZipInputStreamto find out what’s available. It will mean you’ll have different code for directories and jar files though.One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.