java 运行 .jar 时 getResourceAsStream 文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16010539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getResourceAsStream filepath while running .jar
提问by user2281673
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.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?
当playerhit.mp3
文件与MP3.class
运行的文件在同一个包中时,此代码工作正常。我将它作为 .jar 运行。如果我将文件路径更改为类似的内容,/src/data/audio/playerhit.mp3
则它不再起作用。在作为 .jar 运行时,是否可以访问与包根目录不同的文件路径?
回答by mthmulders
Take a look at the Javadoc for getResourceAsStream(...)
.
查看Javadoc forgetResourceAsStream(...)
.
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 .
.
如果参数以 a 开头/
,则资源的绝对名称是名称后面的部分/
。否则,绝对名称采用以下形式:
modified_package_name/name
其中modified_package_name
是此对象的包名称,/
替换为.
。
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.
因此,如果您playerhit.mp3
位于包结构的根目录中,则应将其引用为/playerhit.mp3
. 如果它在 中/src/data/audio/
,您可能应该使用/data/audio/playerhit.mp3
- 但请检查您的 JAR 文件的内容以确保。
回答by Puce
Check first if the file is actually in the jar.
首先检查文件是否确实在 jar 中。
Check the location inside the jar.
检查罐子内的位置。
Relative path: current package
相对路径:当前包
Absolute path: root of jar
绝对路径:jar的根目录