Get resource from jar

2020-01-25 02:44发布

问题:

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?

回答1:

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


回答2:

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

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


回答3:

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


回答4:

use:

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