简体   繁体   中英

Creating JAR file and using in command prompt?

Okay so I already followed the Java tutorial for creating a JAR file and even creating the Manifest.txt that goes along with it. I am highly confused and I got to the point where I was running the JAR in the command prompt but it wasn't referring to the other class I was using in my main program.

I have two .class files that I am using, javagame.class and sound.class .

It was finally loading the main class but when it needed to refer to the sound.class file it was saying that it doesn't exist, a NoClassDefFoundError

I did 'jar cfm myjar.jar Manifest.txt javagame.class sound.class' in the cmd prompt then

jar cfe app.jar javagame javagame.class

Finally I did java -jar app.jar to run the JAR and I got the error above where it couldn't find the sound.class file.

Somebody please help I'm highly confused.

Consider a directory structure for your .java & .class file:

HelloWorld(root directory)
   |
   |\src\HelloWorld.java
   |
   |\classes\mypackage\HelloWorld.class

HelloWorld.java will look like

package mypackage;

public class HelloWorld {

    public static void main(String[] args){
       System.out.println("Hello World");
    }
}

To compile and get the class file in classes folder use the -d option in javac like:

F:\HelloWorld\src>javac -d ../classes HelloWorld.java

to add all .java files you can use *.java

To create a executable jar of HelloWorld execute the below command from classes directory:

F:\HelloWorld\classes>jar cfe HelloWorld.jar mypackage.HelloWorld mypackage/HelloWorld.class

after the jar command the options cfe means:

  1. c : indicates that you want to create a JAR file.
  2. f : indicates that you want the output to go to a file rather than to stdout.
  3. e : overrides the manifest's Main-Class attribute.


Finnaly, to run the generated jar file, execute below command:

F:\HelloWorld\classes>java -jar HelloWorld.jar

Output: HelloWorld

Suppose, If you want to specify your own manifest.mf file, then go for

jar cfm MyJar.jar Manifest.txt mypackage/*.class

This is quite off you request, but nonetheless, it is much, much simpler . I'll demonstrate how to create a JAR file using BlueJ .

  1. Open BlueJ and the project that contains all your code. (You can import non-bluej : go to Projects , Open Non BlueJ and then selct the folder containing your code.) 在此处输入图片说明

  2. Go to Project and select Create Jar File... . Select your Main class (Here, it is NumberSystems.java for me). The rest you can customize... 在此处输入图片说明

  3. Save your file... 在此处输入图片说明

And you're all done! As simple as that. You can now execute this from cmd .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM