How should I use getResource() in Java?

Chap picture Chap · Jun 19, 2011 · Viewed 16k times · Source

This question is asked in numerous places, with myriad small variations. (Such as Java - getClassLoader().getResource() driving me bonkers among others.) I still can't make it work.
Here's a 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've hard-coded the path to the directory containing the clip file, which is there, and is in the same directory as my .class file. Alas, the commented-out code just returns a null value for url.

Most other posts seem to deal with getResourceAsStream(). I think I'm supposed to be using getResource(). Is that making the difference?

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

Answer

Mark Peters picture Mark Peters · Jun 19, 2011
String clipName = "Chook.wav";

When using getResource, the string you pass in must be either an absolute name or be valid relative to a certain class. Since you're using ClassLoader.getResource() and not Class.getResource(), it must 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 a package/folder within that path, and "Chook.wav" exists in that folder. If that's the case, then you need to use /ibm1260/Chook.wav (or potentially ibm1260/Chook.wav, I don't typically use the class loader for resource lookups) as the name of the file that you pass in to getResource().

Either way, you need to make sure that the file is copied into the location of your compiled code and that the root folder is on the classpath.