简体   繁体   中英

How to convert Java program into jar?

A little help from you all... I was trying to convert a simple java program into jar but nothing seems to have happened. I have 2 files: Tester.java , Tester.Class. Then I used this command line:

jar -cvf Tester.jar Tester.class

The .jar file was created but nothing seems to work. What did I miss?

To run the program in the jar file you created you would need to execute

java -cp Tester.jar your.package.Main

A more convenient way to execute the jar is to be able to do

java -jar Tester.jar

That, however, requires that you specify the main-class in a manifest file, that should be included in the jar-file:

  • Put

     Manifest-Version: 1.2 Main-Class: your.package.Main 

    in manifest.txt

  • And to create the jar:

     jar cvfm Tester.jar manifest.txt Tester.class 

As Matthew Flaschen commented answered , you'll need to have a "manifest file" in your jar, and that should contain Main-Class header pointing out which is the main class in the jar to execute. The answer by aioobe perfectly illustrates the simplest way to do this.

But instead of doing that always "manually", I'd recommend that you take a look at a build tool , such as Apache Ant (or Maven , but that's probably a bit harder to get started with), which are very commonly used to automate these kind of build sequences.

With Ant, you'd create a "buildfile" (most commonly named build.xml ) like this:

<project name="Tester">
    <target name="build" 
            description="Compiles the code and packages it in a jar.">

        <javac srcdir="src" destdir="classes" source="1.6" target="1.6"/>

        <jar destfile="Tester.jar">
            <fileset dir="classes"/>
            <manifest>
                <attribute name="Main-Class" value="com.example.Tester"/>
            </manifest>
        </jar>
    </target>
</project>

Now, calling ant build would compile your code and package it in "Tester.jar", which will also contain the correct type of manifest header, so that you can run it with java -jar Tester.jar . (Note that this example assumes that your sources are in "src" directory, relative to where you run the command. You'll also need to have Ant installed of course.)

If you do decide to try out Ant, its official manual will be immensely useful (especially the list of Ant "tasks" which eg shows what options you can give to specific tasks like javac or jar ).

If you wanted to run late this:

java -jar Tester.jar

you should read this tutorial lesson .

Your command will create a jar file. You may need to set the Main-Class manifest header .

我建议使用一些IDE,如Netbeans,Eclipse,IntelliJ IDEA,并专注于您的编程(通过点击构建您的程序)。

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