Java 从jar中获取资源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3831845/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:37:11  来源:igfitidea点击:

Get resource from jar

javaresourcesjar

提问by Victoria Seniuk

I have jar with files:

我有 jar 文件:

myJar/res/endingRule.txt
myJar/wordcalculator/merger/Marge.class

In Marge.java I have code:

在 Marge.java 我有代码:


private static final String ENDINGS_FILE_NAME = "res/endingRule.txt";
....
InputStream inputStream  = getClass().getClassLoader().getResourceAsStream(ENDINGS_FILE_NAME);
.....

但是在此 inputStream 之后为空。如何使用资源?为什么为空?

采纳答案by Paulo Guedes

To retrieve the file inside the jar, use:

要检索 jar 中的文件,请使用:

private static final String ENDINGS_FILE_NAME = "/res/endingRule.txt";
...
InputStream is = getClass( ).getResourceAsStream(ENDINGS_FILE_NAME);

回答by Jon Skeet

Your name looks wrong - incorrect extension andthe wrong kind of slash:

你的名字看起来不对 - 不正确的扩展名错误的斜线:

private static final String ENDINGS_FILE_NAME = "res/endingRule.txt";

回答by David J. Liszewski

The \is being interpreted as an escape character rather than directory separator. File name is also off. Try:

\被解释为转义字符,而不是目录分隔符。文件名也关闭。尝试:

private static final String ENDINGS_FILE_NAME = "res/endingRule.txt";

回答by TameHog

use:

用:

private static final String ENDINGS_FILE_NAME = "res\endingRule.txt";