getResourceAsStream filepath while running .jar

被刻印的时光 ゝ 提交于 2019-12-06 19:43:38

问题


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?


回答1:


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.




回答2:


Check first if the file is actually in the jar.

Check the location inside the jar.

Relative path: current package

Absolute path: root of jar



来源:https://stackoverflow.com/questions/16010539/getresourceasstream-filepath-while-running-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!