OK. So I have a pretty simple question: I want to be able to load a resource (a whole folder) from inside a running .jar file, but I have not been able to get it to work. This is what I have tried (if the class name were “myClass” and the folder being called “myFolder”), but it always throws a NullPointerException:
URL folderURL = myClass.class.getClassLoader().getResource("myFolder/");
String folderPath = folderURL.getPath();
File myFolder = new File(folderPath);
The NullPointerException is always thrown before I create “myFolder”.
Some more info: I have to access the folder from static context. The class that is accessing the folder is NOT in the same directory as the folder itself is in. (The folder is in the root directory inside the jar, the class is a couple subpackages down.)
Does anyone have a solution to my problem? Sorry if I used wrong terminology :P, but anything you can do to help is appreciated.
There’s no way this will work. You’re trying to create a File object from a resource inside a JAR. That isn’t going to happen. The best method to load resources is to make one your package folders a resource folder, then make a Resources.jar in it or something, dump your resources in the same dir, and then use
Resources.class.getResourceAsStream(resFileName)in your other Java class files.If you need to ‘brute force’ the subfiles in the JAR directory pointed to by the URL given by
getResource(..), use the following (although it’s a bit of a hack!). It will work for a normal filesystem too:You can then modify the URL given by
getResource(..)and append the file on the end, and pass these URLs intogetResourceAsStream(..), ready for loading. If you didn’t understand this, you need to read up on classloading.