Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java creating .jar file

Tags:

java

jar

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.

like image 504
user433947 Avatar asked Jan 04 '11 20:01

user433947


People also ask

Why do we create JAR file in Java?

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.

How do I create a runnable jar in Java?

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.


2 Answers

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 

See also

  • Creating a JAR File
  • Setting an Application's Entry Point with the JAR Tool
like image 135
João Silva Avatar answered Oct 14 '22 11:10

João Silva


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.

like image 39
Sean Avatar answered Oct 14 '22 10:10

Sean