Building a standalone Java command line app with Netbeans

Pretty simple one really, and it was – once I remembered / found out.

Seeing as I swap around from IDE to programming language, to OS I realised the other day that I didn’t know how to build a self contained command line java app (e.g. I had written a simple program and I wanted to ship it with the mysql driver) within Netbeans.

So after a bit of searching, and being put off by the prospect of using ant I discovered a way to do it… I thought I would write this in the hope I won’t forget and to help others (took a little while to find this answer).

Let imagine we have a simple Java program, good old hello world (see below)

public static void main(String[] args)
      Connection connection = null;
      Statement statement = null;


           connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/svm","username","password");

           statement = connection.createStatement();
      catch(Exception e)
           System.out.println("Oh boy - "+e.toString());
           catch(Exception e)
                 System.out.println("Oh by there is a problem! "+e.toString());

      System.out.println("Hello world");

And further to this, the simple program also connects to a MySQL database…

Now, you can see the desire… you to want to ship the jar including the mysql library? Well, this can be achieved really easily (in Netbeans). Just do the following:

  • Within the root directory of the project there is a file named – build.xml
  • Open this file in Netbeans, you will notice some XML at the top of the file about project name etc, within the open project element you see a lot of comments.
  • Scroll to the end of the file
  • Just before the closing element of project e.g. </project> insert the following example lines
 <target name="-post-jar" >
     <jar jarfile="${dist.jar}" update="true">
         <zipfileset src="${dist.jar}" includes="**/*.class"/>
         <zipfileset src="dist/lib/mysql-connector-java-5.1.6-bin.jar" excludes="META-INF/*"/>

This is the specific entries for adding the MySQL library to your jar file. You will note that it is referencing the library from my /project/dist/lib/ directory.

And that’s it! Clean and build and you find your jar is bigger and contains your library!!!! Brilliant – ship it to the world now 🙂

My source


Tags: , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: