Victoria Seniuk
Victoria Seniuk

Reputation: 1414

Get resource from jar

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?

Upvotes: 16

Views: 27500

Answers (4)

TameHog
TameHog

Reputation: 950

use:

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

Upvotes: 0

Dave L.
Dave L.

Reputation: 11228

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

Upvotes: 1

Paulo Guedes
Paulo Guedes

Reputation: 7259

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

Upvotes: 16

Jon Skeet
Jon Skeet

Reputation: 1499770

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

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

Upvotes: 6

Related Questions