nix
nix

Reputation: 2285

Why cannot JAR find resources?

I have two classes (Play and editor). editor uses Play. Play uses some external files. I imported them into Eclipse in order to address them straight (as you can see on the first screenshot). enter image description here I want JAR to be able to contain these files withing and be able to work with (import) them. Is that possible? What options should I choose while exporting project to JAR?

Upvotes: 1

Views: 1866

Answers (1)

Ashutosh Jindal
Ashutosh Jindal

Reputation: 18867

If you want to use the .wav files from within a jar then instead of doing String path = System.getProperty("user.dir"); and then loading the wav files from there, try doing something like :

InputStream stream = Play.class.getResourceAsStream("/result.wav");

From here, it seems that AudioSystem does have an overloaded getAudioInputStream which accepts an InputStream instead of a File object (as in your code). So you could have something like :

public class Play{
    public AudioInputStream find(String s) throws UnsupportedAudioFileException, IOException{
        // Probably some try catch over the next statement to log the error if `result.wav` is not found.
        InputStream stream = Play.class.getResourceAsStream("/result.wav");
        return AudioSystem.getAudioInputStream(stream); 
    }
}

For the above to work all your *.wav files must be copied to a source folder so that they are present on the classpath. To do that you could move *.wav into sint/src to start with (and then into a proper wav folder later on if needed). That would put them in the root of the classpath / and allow them to be referred to like so : /result.wav , /x_SECOND.wav etc.

Working Code

Here is a bit of working code to test out AudioInputStream from here :

public class A {    
    @Test
    public void testAudioInputStream() throws UnsupportedAudioFileException, IOException {
        InputStream stream = A.class.getResourceAsStream("/result.wav");
        System.out.println(stream != null);
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(stream);
        System.out.println(audioInputStream != null);
    }    
}

The above code worked fine for me and I got two true in the console.

GIT Hub Repo with Test project

You should be able to import the project in this zip and see the code working.

Do you need a 'Fat Jar' ?

A bit off-topic, but if you need to build a fat jar that includes all the jars needed by your project to run and is a single executable then try using http://fjep.sourceforge.net/ plugin to build a fat jar.

You can export a java project containing jars using the File -> Export -> Other -> One Jar Exporter. The jar that's thus built is an executable jar and needs nothing else to run.

Upvotes: 3

Related Questions