Java Program Distribution with JAR Files

When I chose to learn how to code in Java, one of the biggest factors that played into that decision was the fact that it compiles into bytecode, which can be run on any machine with the Java Virtual Machine (JVM) running on it. I wanted to be able to write programs for friends to run on their computers. While working in my IDE of choice, simply pressing the “compile” button would create an executable JAR file that I could distribute, however I decided to probe further and discover how to take a regular java file, compile it and distribute it all from a command line setting.

Let’s start off by assuming that we have a java file with no compilation errors. The class is called myCode, and it is in the myPackage package. Open your command prompt and navigate to the “myPackage” directory with your source files. Compile everything into CLASS files using this command:

javac myCode.java

For projects with multiple source files, you can list multiple files or use *.java to compile all files in the directory. Now your directory will have two files in there, myCode.java and your class file, myCode.class and you are ready for the next step, creating your manifest file. First, navigate one directory up, so that you are in the directory containing the “myPackage” directory. The manifest is a simple text file which tells the jar file what class file to look at first when it comes time to execute the program. In this case the contents of manifest would be:

Main-Class: myPackage.myCode

Notice that I include the package specification. It is also a good idea to end the one-line file with a newline, as some systems require it. Your manifest can be named anything you like, but it’s usually best to stick to standard names. Now to create your executable JAR file. Simply run the following line of code, which I will explain shortly:

jar cmf manifest myCode.jar myPackage

You now have an executable myCode.jar file that you can run from the command line like this:

java -jar myCode.jar
Published
Categorized as Java

By Bryan Young

Bryan Young is a staff writer for WebProNews.

Leave a comment