4

I am trying to package a Java project into a runnable jar using Eclipse (version Kepler SR2). The project is using Maven (which has been fored onto me and I don't know much about it). The problem is that the project runs fine within Eclipse, but after export to Jar it doesn't find any of the required resources anymore.

Here is the folder structure:

+src
  +main
     +java
       <packages with source code>
     +resources
       <folders with static resources>
  +test
     +java
       <unit test classes>

I have also added the resource folder to the build path.

The resources are loaded using

File myFile = new File(getClass().getClassLoader().getResource("resourcePath").getPath());

This line works perfectly fine when executing the program from Eclipse, but it fails with an NPE when using the executable jar that I created with "Export>Java>Runnable Jar".

I have already to use the standard Jar export with the options "Export generated class files and resources" and "Add directory entries" checked. This leads to the same problem, though.

What do I need to do in order to correctly export the resources into the Jar?

Thanks!

Martin

martin_wun
  • 1,599
  • 1
  • 15
  • 33
  • http://stackoverflow.com/questions/15749192/how-do-i-load-a-file-from-resource-folder may perhaps help you? – kow Sep 27 '14 at 12:07
  • [This answer](http://stackoverflow.com/a/26058779/2587435) doesn't use maven, but you are experiencing the same problem. It gives a decent explanation and solutions – Paul Samsotha Sep 27 '14 at 12:19

2 Answers2

1

Use maven-assembly-plugin: Reference: Building a runnable jar with Maven 2 http://www.javavids.com/video/how-to-create-runnable-jar-file-with-maven.html

Community
  • 1
  • 1
Smrutiranjan Sahu
  • 6,911
  • 2
  • 15
  • 12
0

Maven's default strategy is to copy resources in a separate "resources" folder and to add that folder to the class path.

When you import a Maven project, Eclipse is configured to treat the “project/src/main/resources” folder as a source folder but to exclude everything from being exported **. The temporary output folder is “project/target/classes”. You can see this in the java build path. So, when you are inside Eclipse, resources are copied to the right temporary folder and everything works fine. When you ask Eclipse to build a runnable JAR, it copies resources to the “resources” folder but does not add this folder to the classpath. You can see this if you open the JAR.

You have three solutions (from better to worst):

  1. Use maven to build your runnable JAR. See: Building a runnable jar with Maven 2
  2. Edit Eclipse’s build path to remove the “**” exclusion. This change will be overwritten every time you sync with Maven
  3. Move your resources. See: Change maven's export resource directory
cquezel
  • 3,859
  • 1
  • 30
  • 32