Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 725
Victoria Seniuk Avatar asked Sep 30 '10 14:09

Victoria Seniuk


People also ask

Can you get source code from a JAR file?

Jar files are archive files that contains of a lot of different java classes (files). You can use winzip/winrar to open the jar files and you can see those java classes in jar files. Typically you can use a Java decompiler to decompile the class file and look into the source code.

Do jar files contain resources?

jar ) contain your executable classes and resource files. A jar can also contain other jar files, which is useful when your program needs some library which is packaged in a jar.


2 Answers

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);
like image 117
Paulo Guedes Avatar answered Oct 07 '22 03:10

Paulo Guedes


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

private static final String ENDINGS_FILE_NAME = "res/endingRule.txt";
like image 33
Jon Skeet Avatar answered Oct 07 '22 03:10

Jon Skeet