getResourceAsStream filepath while running .jar

user2281673 picture user2281673 · Apr 15, 2013 · Viewed 10.8k times · Source

My code:

BufferedInputStream bis =
  new BufferedInputStream(getClass().getResourceAsStream("playerhit.mp3"));

This code works fine when the playerhit.mp3 file is in same package as the MP3.classit is running in. I'm running this as .jar. If though I change the file path to something like /src/data/audio/playerhit.mp3 it doesn't work anymore. Is there anyway to access different filepath than root of the package while running as .jar?

Answer

mthmulders picture mthmulders · Apr 15, 2013

Take a look at the Javadoc for getResourceAsStream(...).

If the argument begins with a /, then the absolute name of the resource is the portion of the name following the /. Otherwise, the absolute name is of the following form: modified_package_name/name Where the modified_package_name is the package name of this object with / substituted for ..

So, if your playerhit.mp3 is in the root of your package structure, you should reference it as /playerhit.mp3. If it's in /src/data/audio/, you should probably use /data/audio/playerhit.mp3 - but check the contents of your JAR file to be sure.