Using Jar Files and Java Webstart

You can create executable jar files that can be "run" or executed by double-clicking the jar file. These also form the basis for code you can launch via Java webstart.

You can create the jar file from within Eclipse (see below). But if the code reads images or other files to work you'll have to refactor the code so that it uses a URL-based location system to find resources rather than a file-based resource system.

Opening Files/Images

For example, to open a file named "data.txt" in your code you might use this code:

Scanner scan = new Scanner(new File("data.txt")); // process using scan.hasNext() scan.next() and so on

That code works fine if "data.txt" is accessible from wherever the Java code is running (e.g., your Eclipse folder). But that code won't work when using an executable jar file. Instead you need a URL to locate the file. The code below will work both from within Eclipse/the command line and from a jar file.

Scanner scan = new Scanner(this.getClass().getResourceAsStream("/data.txt")); // process scan.hasNext() and scan.next() The method getResourceAsStream from java.lang.Class returns a stream from a URL. You can also get the URL and the stream in separate steps (which is what getResourceAsStream is doing underneath): URL name = this.getClass.getResource("/data.txt"); InputStream is = name.openStream(); Scanner scan = new Scanner(is); To read images from a file you do something very similar: URL name = this.getClass.getResource("/image.jpg"); Image image = Toolkit.getDefaultToolkit().getImage(name); You can read almost any resource using this technique, and it works both from a jar file and from the file-system/Eclipse.

Executable Jar

From Eclipse select the project you want to jar-up, right click and choose Export as shown below -- you can also choose Export from the Ecllipse File-menu which yields the same dialog (on the left below):

After choosing Export, select Java/jar file as shown in the dialog on the right:

*selectexport* jar export

You'll have to choose a name for the jar file and you'll have to specify the launch-point for the jar file as shown in this dialog where you will Browse to locate the class with public static void main you want.

jar main

Once you've created the executable jar file you can locate it and double-click it to run. That should work fine if you've done the URL-reading stuff shown above.

JNLP, Java web-start

Once you've created an executable jar file you can launch it from the web via Java webstart. Use this article as a start. If the webserver you're running from doesn't associcate the right mime type with .jnlp files you'll be out-of-luck for the casual user. But for the sophisticated user they can download the .jnlp file and use javaws from the commandline:
  javaws foobar.jnlp