Gravatar of Jeroen Jeroen Pelgrims

Automatically add library jar contents to executable jar with Netbeans

Posted on in java, netbeans, software-development

Say you have a Java project in Netbeans with a library jar added. In my case this was SQLiteJDBC, an SQLite JDBC driver for Java applications.

When you build the project ("Clean and build project") a folder dist will be created with as contents:

  • Your executable jar file
  • A lib folder with the jar files of your added libraries inside

In your executable jar file (it's actually a zip file, you can open it with Winrar for example) there is a folder called META-INF with inside a file called MANIFEST.MF.

Class-Path: lib/sqlitejdbc-v056.jar

This line in MANIFEST.MF makes sure that your executable jar file knows that the jar file for the SQLiteJDBC driver library is in lib/sqlitejdbc-v056.jar

Now, the problem for me was that I wanted a single executable, not an executable with some added library files. With Java you can easily solve this problem by copying the contents of your library jars into your executable jar. This means opening sqlitejdbc-v056.jar and opening the created executable jar with Winrar and dragging all the contents from the library jar to the executable jar.

Now, I'm quite lazy and I want that when I click the 'Clean and Build' button this all happens automatically.

In your Netbeans project folder ("nbproject") there is a file called 'build-impl.xml'. This file defines how your executable jar will be built.

Look for this line:

<target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class+mkdist.available" name="-do-jar-with-libraries">

Within this block there is a block called 'copylibs'.

<fileset dir="${build.classes.dir}"/> defines the files that will be copied in to the executable jar. (your compiled .java files)

What we want to add is this line:
<zipfileset src="lib/SqliteJDBC/sqlitejdbc-v056.jar" includes="**/*.java **/*.class"/>

This will make sure that the content of sqlitejdbc-v056.jar will be copied into the executable jar file.

The only downside is that in the manifest file the library jars still get added to the classpath and the files still get copied into the dist/lib folder.

Update:

Apparently since last working on that project where I needed this I changed some stuff. A somewhat updated explanation:

In the root directory of your project you should have a build.xml file. You need to open this file and look for the tag <copylibs>

Within that tag there should be a tag called <fileset>

like this: <fileset dir="${build.classes.dir}"/>

Below that line paste the zipfileset one. (One for each library jar you need included, I’ve only tried it with one library though.)

This post is written by Jeroen Pelgrims, an independent software developer who runs Digicraft.eu.

Hire Jeroen