运行.jar时获取getResourceAsStream文件路径 [英] getResourceAsStream filepath while running .jar
问题描述
我的代码:
BufferedInputStream bis =
new BufferedInputStream(getClass().getResourceAsStream("playerhit.mp3"));
当 playerhit.mp3
文件与正在运行的 MP3.class
在同一个包中。我将其作为.jar运行。如果我将文件路径更改为 /src/data/audio/playerhit.mp3
,它将不再起作用。在以.jar运行时,是否仍然可以访问不同于文件包根目录的文件路径?
This code works fine when the playerhit.mp3
file is in same package as the MP3.class
it 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?
推荐答案
看看 Javadoc for getResourceAsStream( ...)
。
如果参数以 /
开头,则资源的绝对名称是以下名称的一部分 /
。否则,绝对名称的格式如下:
modified_package_name / name
其中 modified_package_name
是此对象的包名称, /
替换为。
。
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 .
.
因此,如果 playerhit.mp3
位于包结构的根目录中,则应将其引用为 /playerhit.mp3
。如果它在 / src / data / audio /
中,你应该使用 /data/audio/playerhit.mp3
- 但请检查JAR文件的内容以确定。
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.
这篇关于运行.jar时获取getResourceAsStream文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!