saplingPro
saplingPro

Reputation: 21329

Giving a relative path, so that the sound works as I run the jar file on any machine

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

Upvotes: 0

Views: 347

Answers (2)

Perception
Perception

Reputation: 80623

In cases like this it's best to load the resource relative to the root classpath:

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

You can also get the resource as a stream:

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

The main difference between this and Class.getResource is that Class.getResource assumes that the supplied path is relative to its location in the class hierarchy. So given the relative path "/sounds/file.wav", calling getResource from a class utility.Constants, would attempt to resolve the file.wav resource from package utility.sounds. Whereas using the class loader and the same relative path, the resource would be resolved from sounds. A subtle but important difference.

Upvotes: 1

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20751

try this....

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

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

Upvotes: 1

Related Questions