I'm learning Java and I have a problem. I created 6 different classes, each has it's own main()
method. I want to create executable .jar
for each class, that is 6 executable .jar
files.
So far I tried
java -jar cf myJar.jar myClass.class
and I get 'Unable to access jarfile cf'. I'm doing something wrong but I don't know what. I'm also using Eclipse IDE if that means something.
Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (. class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece.
To export your project, right-click it and select Export. Select Java > Runnable JAR file as the export destination and click Next. On the next page, specify the name and path of the JAR file to create and select the Launch configuration that includes the project name and the name of the test class.
In order to create a .jar file, you need to use jar
instead of java
:
jar cf myJar.jar myClass.class
Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)
) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class
header (e.g., Main-Class: myClass
).
However, as Mark Peters pointed out, with JDK 6, you can use the e
option to define the entry point:
jar cfe myJar.jar myClass myClass.class
Finally, you can execute it:
java -jar myJar.jar
Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With