javaeclipseresourcesprojectembedded-resource

Where should I put my resources for a Java program?


I'm programming in Java using Eclipse.

I have recently tried playing a sound file in my program. I did this:

URL url = this.getClass().getResource("ih.wav");
audioIn = AudioSystem.getAudioInputStream(url);
clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();

This only worked, when I tried to put ih.wav in the bin folder, as if the bin folder was the "base folder" for my project. Putting the file in the main folder of the project, didn't work. Putting it in the src folder, didn't work too.

Can someone explain to me where to put my resources for Java programs? Also, does it matter if I import the resources into Eclipse? Thanks

EDIT:

Tried to create a resources folder in the main project folder, still gives me a NullPointerException:

        URL url1 = this.getClass().getResource("res/ah.wav");
        audioIn = AudioSystem.getAudioInputStream(url1);
        clip1 = AudioSystem.getClip();
        clip1.open(audioIn);

        URL url2 = this.getClass().getResource("res/eh.wav");
        audioIn = AudioSystem.getAudioInputStream(url2);
        clip2 = AudioSystem.getClip();
        clip2.open(audioIn);

        URL url3 = this.getClass().getResource("res/ih.wav");
        audioIn = AudioSystem.getAudioInputStream(url3);
        clip3 = AudioSystem.getClip();
        clip3.open(audioIn);

        clip1.start();
        clip2.start();
        clip3.start();

Solution

  • Best practice would be to create a folder (depending on your package structure) that is called either res or resources where you will keep project related resources such as any images or sound files.

    Depending on preference, either put this folder in your main project folder MyProject/res or put it inside the relevant package, e.g. main.java.res

    EDIT

    To adhere more to your question, I'm not too familiar with the getResources() method, so instead I would personally recommend using some code similar to:

    File file = new File("ih.wav");
    audioIn = AudioSystem.getAudioInputStream(file);
    clip = AudioSystem.getClip();
    clip.open(audioIn);
    clip.start();
    

    That should produce the results you are looking for, given that you change the path of he file accordingly (e.g. "main/resources/ih.wav" or wherever you are storing the file.