Java resource as file

Mantrum picture Mantrum · Mar 24, 2009 · Viewed 170k times · Source

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)?

Answer

Chris Conway picture Chris Conway · Jul 7, 2009

I had the same problem and was able to use the following:

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()