Create Runnable JAR with .properties files using Java Eclipse

22,224

Solution 1

This is based on memory, but I'm fairly sure that properties files aren't automatically loaded from a jar. The idea is that the properties files should be easily modifiable. Otherwise, the values might as well just be in a class file.

If you tried to access a properties file from anywhere else, this shouldn't be a problem.

This is also why you seldom see jar files packaged alone. There is usually something else that needs to be loaded.

Is there a reason this behavior is necessary?

Solution 2

Here's what I do and it works reliably:

  1. put your .properties file under the source tree in your Eclipse project
  2. make sure all the .properties files in the source tree get copied to the build tree. I use ant with a <copy> task declared before the <jar> task in the same target.
  3. my classes access the properties files with getResourceAsStream()

I am not sure what the Eclipse Export utility does but you might try looking at ant, as it may give you more control over the build process.

Share:
22,224

Related videos on Youtube

Beier
Author by

Beier

Updated on July 09, 2022

Comments

  • Beier
    Beier almost 2 years

    I'm trying to build a runnable JAR using Eclipse's Export function. everything works fine except several .properties files I have under the root directory.

    I added all the .properties files into Build Path, and they appears under 'Order and Export' tab in Java Build Path dialog.

    However, when I try to run the Export, I got the following errors:

    Could not read JAR file 'log4j.properties'. Reason: error in opening zip file error in opening zip file error in opening zip file

    The Runnable JAR file is actually created, but with no .properties files in it. why does it try to export .properties files as ZIP files? how to make this work?

    Eclipse Build id: 20090621-0832

  • Beier
    Beier over 14 years
    what you said makes total sense to me. I don't really need to put properties files into JAR, I looked at log4J, and it doesn't have .properties file in JAR neither, but rather you need to include it yourself
  • matbrgz
    matbrgz almost 14 years
    log4j reads from a file. To read from a jar in the classpath you must use a getResource* method.