Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use getResource() in Java?

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?

like image 877
Chap Avatar asked Feb 23 '23 20:02

Chap


2 Answers

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.

like image 78
Mark Peters Avatar answered Mar 02 '23 20:03

Mark Peters


The getResource and getResourceAsStream methods are for accessing resources on the classpath. You seem to be trying to access some resource that is not on the classpath.

The logic that getResource and getResourceAsStream use to locate resources is essentially the same. The difference between the methods is that one returns a URL, and the other an InputStream.


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

This is not that hard at all. You just need to understand how classpaths work ... and make sure that you use a resource name that resolves to a resource that you've put in the correct location in one of the directories or JAR files on the classpath.

Or if the resource is not "part of" your application, don't access it this way.

like image 36
Stephen C Avatar answered Mar 02 '23 21:03

Stephen C