0

In the utility package as shown in the snapshot, there is a class Constants. In the same directory as of utility there is a folder called sounds, also shown in the snapshot. Till now I have been giving the complete path of the .wav files.

Like W:/UnderTest/Blaah/Blaaaaah/Foo/sounds/file.wav

How should I give the path, so that when I make a .jar file of it, the sound still works. I tried this :

../sounds/Player_1.wav

but it doesn't work and I get java.io.FileNotFoundException: ..\sounds\Player_1.wav (The system cannot find the path specified)

enter image description here

4

2 回答 2

1

try this....

URL url = Constants.class.getResource("/sounds/file.wav");

the url in which now gets the path of your file....

于 2013-04-07T04:53:00.310 回答
1

在这种情况下,最好加载相对于根类路径的资源:

URL soundURL = Thread.currentThread().getContextClassLoader()
        .getResource("/sounds/file.wav");

您还可以将资源作为流获取:

InputStream soundURLStream = Thread.currentThread().getContextClassLoader()
        .getResourceAsStream("/sounds/file.wav");

这和它之间的主要区别Class.getResourceClass.getResource假设提供的路径是相对于在类层次结构中的位置。因此,给定相对路径“/sounds/file.wav”,getResource从 class调用utility.Constants,将尝试file.wav从 package 解析资源utility.sounds。而使用类加载器和相同的相对路径,资源将从sounds. 一个微妙但重要的区别。

于 2013-04-07T05:09:07.210 回答