How to use getResource () in Java?

This question is asked in many places, with many small variations. (For example, Java is getClassLoader (). GetResource () makes me bonkers , etc.) I still can't get it to work.
Here's the code snippet:

String clipName = "Chook.wav"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // URL url = classLoader.getResource(clipName); URL url = new URL("file:///Users/chap/Documents/workspace/the1620/bin/ibm1620/" + clipName); ais = AudioSystem.getAudioInputStream(url); 

This works - note that I hardcoded the path to the directory containing the clip file, which is, and is in the same directory as my .class file. Alas, the comment code simply returns a null value for the URL.

Most of the other posts seem to relate to getResourceAsStream (). I think I should use getResource (). Does it really matter?

It just can't be that hard. Any clues?

+4
source share
2 answers
 String clipName = "Chook.wav"; 

When using getResource string you pass must be either absolute or valid relative to a particular class. Since you are using ClassLoader.getResource() and not Class.getResource() , this should be an absolute path.

Without seeing your actual file hierarchy, I can only guess that “bin” is the root of your compiled classes and resources, and “ibm1260” is the package / folder inside this path, and “Chook.wav” exists in this folder. In this case, you need to use /ibm1260/Chook.wav (or potentially ibm1260/Chook.wav , I usually do not use the class loader to search for resources) as the name of the file that you pass to getResource() .

In any case, you need to make sure that the file is copied to the location of your compiled code and that the root folder is in the class path.

+4
source

The getResource and getResourceAsStream are used to access resources in the class path. It seems you are trying to access some resource that is not in the classpath.

The logic of using getResource and getResourceAsStream to find resources is essentially the same. The difference between the methods is that one returns a URL and the other returns an InputStream .


It just can't be that hard. Any clues?

It is not that difficult. You just need to understand how classes work, and make sure that you use a resource name that resolves the resource that you placed in the right place in one of the directories or JAR files in the class path.

Or, if the resource is not a “part” of your application, do not access it that way.

+4
source

All Articles