Saturday, September 22, 2012

Standalone Java Application

I've been using java for years, but I've never really used it to create a standalone application that actually did something. In school we were spoon fed projects to work on. At work I add to or fix the current java web applications. What I really want is to write programs that do what I want them to do. But what is that? I've tried asking others what would be helpful, but without real passion for what needs are out there, I'm not going to get anything done. It's time to start coding and let the purpose follow. My current goal is to start coding some helpful utility applications, so when I have a real purpose I'll have the means to jump right in. So skipping command line execution of plain class files... I started with creating Executable Jar files.

Requirements for the Executable .jar

Class files
Something with a main method to run. I'll be starting with the quintessential 'Hello World' project.
Manifest file
The manifest tells the jvm what you want the point of entry to be for the jar.

Hello World!

My little java class lives in the demo package, and prints "Hello World!" and then lists the arguments passed in.
package demo;
public class HelloWorld {
public static void main (String[] args) {
System.out.println("Hello World!");
for (String each : args)
System.out.println (each);
Compile the classfile (commandLine$ javac and you're good to go.


This file is just one line, and ends with a newline
Main-Class: demo.HelloWorld

Putting it all together

Here's what I have so far

 The .java file isn't really necessary from this point forward, but if you want to go back and look inside your jar for the source code you'll want to keep it around.

Create the .jar

Use the jar utility to package up the jar. cmfv = create, manifest (filename), filename (for jar), verbose

jar cmfv MANIFEST.txt demo.jar demo
added manifest
adding: demo/
adding: demo/
adding: demo/MANIFEST.MF
adding: demo/HelloWorld.class

The Result

All said in done, we're left with demo.jar
When you run java -jar demo.jar in the command-line, you get the result below
steve:~/Desktop$ java -jar demo.jar
Hello World!
You can also add extra parameters and they will be printed below
steve:~/Desktop$ java -jar demo.jar what\'s\ up?
Hello World!
what's up?

No comments:

Post a Comment