开发者

Get resource from jar

开发者 https://www.devze.com 2023-01-18 10:30 出处:网络
I have jar with files: myJar/res/endingRule.txt myJar/wordcalculator/开发者_开发百科merger/Marge.class

I have jar with files:

myJar/res/endingRule.txt
myJar/wordcalculator/开发者_开发百科merger/Marge.class

In Marge.java I have code:


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

But after this inputStream is null. How to work with resources? Why null?


To retrieve the file inside the jar, use:

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


Your name looks wrong - incorrect extension and the wrong kind of slash:

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


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";


use:

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

精彩评论

暂无评论...
验证码 换一张
取 消