|
|
How to create a runnable Jar FileCompile your class files into an executable JarHow to compile and run .java files from windows command prompt How to pass parameters to class from command prompt
Before you learn how to create a Jar file, you should be proficient compiling and running Java source files from the command prompt. This tutorial will be using windows Vista but should also work with XP. There are many utilities out there that make it easy to create a Jar file, but I will illustrate how to do it via the windows command prompt.
What is a Jar File?
Before anything else
We are going to need at least one class to compile into a jar. I will use a class called JarDemo. First, let's compile the JarDemo.java file into a class file. I recommend using the class I've created. import javax.swing.JOptionPane; public class JarDemo{ public static void main(String[] args){ String inputValue = JOptionPane.showInputDialog("Type Some Input"); JOptionPane.showMessageDialog(null, "You input " + inputValue); } } Step 1: Locate the Jar utility in the JDK folder
Step 2: Create themanifest fileSince you could potentially be compiling many files into one jar file, Java needs to know which one will have the main method. Our example is a bit more trivial since we're just compiling one class into a Jar. Nonetheless, the way that Java knows which of classes has the main method is from a single line in what's known as a manifest file. A manifest file can be a text file made with notepad. I called my manifest file manifest.txt, my manifest file says:Main-Class: JarDemoAs you can see themanifest file states that the main-class is JarDemo. Warning: A subtle yet critical point is that you MUST end the manifest file with an empty new line.
Last Step: Compile The Jar!
1)Use the command prompt to navigate to where the JarDemo.class and manifest.txt file are saved and type : C:\> C:\Path\to\jdk\bin\jar cvfm jarDemoCompiled.jar manifest.txt JarDemo.class
C:\> jar cvfm jarDemoCompiled.jar manifest.txt JarDemo.classWhen I don't usde the shortcut on my computer, I must type: C:\> C:\"Program Files"\Java\jdk1.6.0_02\bin\jar cvfm jarDemoCompiled.jar manifest.txt JarDemo.classcvfm means "create a jar; show verbose output; specify the output jar file name (jarDemoCompiled.jar); specify the manifest file name(manifest.txt) and use the file JarDemo.class to create the jar Here's the actual screen shot from my command prompt. Remember the path to jdk\bin\jar will be similar on your computer but almost definitely not exactly the same as mine. What if you want to compile all .class files in the folder into the jar? No problem, instead of the last line up above, type: C:\> C:\Path\to\jdk\bin\jar cvfm jarDemoCompiled.jar manifest.txt *.class Hopefully, at this point you have a picture like I have below in your folder. Just click on the Jar file and your program should run! |