4

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?

4

2 に答える 2

5
String clipName = "Chook.wav";

を使用する場合getResource、渡す文字列は絶対名であるか、特定のクラスに対して有効である必要があります。ClassLoader.getResource()and notを使用しているClass.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.

于 2011-06-19T05:40:25.820 に答える
4

getResourceメソッドとメソッドは、クラスパス上のgetResourceAsStreamリソースにアクセスするためのものです。クラスパスにないリソースにアクセスしようとしているようです。

とがリソースを検索するために使用するロジックは、基本的に同じgetResourceです。getResourceAsStreamこれらのメソッドの違いは、一方は URL を返し、もう一方はInputStream.


こんなに難しいことはありません。手がかりはありますか?

これはそれほど難しいことではありません。クラスパスがどのように機能するかを理解する必要があるだけです...そして、クラスパス上のディレクトリまたはJARファイルの1つの正しい場所に配置したリソースに解決されるリソース名を使用していることを確認してください。

または、リソースがアプリケーションの「一部」でない場合は、この方法でアクセスしないでください。

于 2011-06-19T05:42:19.210 に答える