Java resource as File Java resource as File java java

Java resource as File


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

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


ClassLoader.getResourceAsStream and Class.getResourceAsStream are 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 ClassLoader could generate data on the fly, based on what resource name it's asked for. If you look at the ClassLoader API (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 ZipInputStream to 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.


Here is a bit of code from one of my applications...Let me know if it suits your needs. You can use this if you know the file you want to use.

URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png");File imageFile = new File(defaultImage.toURI());

Hope that helps.