1

My goal is to create an executable jar from Eclipse. I have an Eclipse project which runs fine with the structure below.

My Eclipse project

src/main/java
-com.main
      ->MyClass

src/main/resources
 ->MyProps.properties

MyClass is able to access MyProps.properties file successfully.

After I export the Eclipse project and create a runnable jar then my jar structure is like below.

MyJar.jar

-com.main
  ->MyClass

-resources
 ->MyProps.properties

When I run the jar file it fails to access the properties file throwing a NullPointerExeception.

My code

InputStream input = MyClass.class.getClassLoader()
                           .getResourceAsStream("resources/MyProps.properties");

When I export my project as an executable jar file, I cannot access MyProps.properties anymore.

Can someone help me please?

Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
Senthil RS
  • 271
  • 3
  • 8
  • 17

2 Answers2

0

You can use code like below to read a properties file on the Class Path:

MyClass.class.getClassLoader().getResourceAsStream("MyProps.properties")
ozOli
  • 1,414
  • 1
  • 18
  • 26
0

In onder to load a file from a jar. You have to use Class.getResource() or Class.getResourceAsStream().

URL properties = ConfigLoaderTest.class.getResource("/resources/MyProps.properties");

This will load the file from your classpath, this means it will also look inside the jars on your classpath (the executable jar is on your classpath automatically). The first '/' indicates to look from the root of the jars on your classpath, you have omitted this in your code.

The URL you can then read like any URL (it will return null if none is found). For instant by using properties.openStream().

Note that it seems you are using the default maven structure src/main/resources, however you have src/main on your eclipse buildpath, so in your jar you get the resources directory. Normal for maven projects is to have src/main/resources on your buildpath. Which would place your properties file in the root of your jar.

thoutbeckers
  • 2,599
  • 22
  • 24
Thirler
  • 20,239
  • 14
  • 63
  • 92