none of the answers I found to this question worked, so I have to ask here: I'm using Eclipse and I have a program that I export as a runnable jar, and it plays an audio, but the audio has to be in the same folder as the exported jar file or else it doesn't play. How can I package it into the runnable jar so that it doesn't need the audio to actually be there? PS: I'm doing things the old-fashioned way so not using a build system (Maven or Gradle) this is my code; it plays an audio file when a button is pressed:
AudioFormat audioformat = null;
DataLine.Info info = new DataLine.Info(Clip.class, audioformat);
try {
Clip audioclip = (Clip) AudioSystem.getLine(info);
File audio1 = new File("audiofile.wav");
AudioInputStream audiostream = AudioSystem.getAudioInputStream(audio1);
audioformat = audiostream.getFormat();
audioclip.open(audiostream);
audioclip.start();
audiostream.close();
} catch (LineUnavailableException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedAudioFileException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
```
use
getResourceAsStream:Where your jar ends up looking like this:
Where
Main.classhere is your main class, with package header "package com.foo.mobbs8;" -getResourceAsStreamlooks in the same 'directory' as where the class file is, regardless of where that might be (on disk, in a jar, loaded from the network - doesn't matter).Eclipse should treat any non-java file in a 'src' directory as a file to be included verbatim in any exported jar, although you really ought to move to an actual build system sooner rather than later.
If you want to put the audio file in the 'root' (as in, it shows up in the jar as just
file.mp3, notcom/foo/mobbs8player/file.mp3) - no problem. Use.getResourceAsStream("/file.mp3")instead (note the leading slash).