我应该如何在Java中使用getResource()? [英] How should I use getResource() in Java?
问题描述
这个问题在很多地方被提出,有很多小的变化。 (例如 Java - getClassLoader()。getResource()驱使我疯狂等。)我仍然无法做到工作。
这是一段代码:
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);
这有效 - 请注意我已经硬编码了包含剪辑文件的目录的路径,其中 , 与我的.class文件位于同一目录中。唉,注释掉的代码只返回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.
大多数其他帖子似乎都处理了getResourceAsStream()。我想我应该使用getResource()。 那会有所不同吗?
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?
推荐答案
String clipName = "Chook.wav";
当使用 getResource
时,你传递的字符串in必须是绝对名称或相对于某个类有效。由于您使用 ClassLoader.getResource()
而不是 Class.getResource()
,因此它必须是绝对路径。
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.
如果没有看到你的实际文件层次结构,我只能猜测bin是你编译的类和资源的根,而ibm1260是一个包/文件夹在该路径中,Chook.wav存在于该文件夹中。如果是这种情况,那么你需要使用 /ibm1260/Chook.wav
(或者可能 ibm1260 / Chook.wav
,我通常不使用类加载器进行资源查找)作为传递给 getResource()
的文件的名称。
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.
这篇关于我应该如何在Java中使用getResource()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!