tags:

views:

375

answers:

5

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?

+3  A: 

If you wanted to run late this:

java -jar Tester.jar

you should read this tutorial lesson.

PeterMmm
+2  A: 

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

Matthew Flaschen
+5  A: 

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
    
aioobe
+1, very clear and concise explanation of the basics
Jonik
+5  A: 

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 e.g. shows what options you can give to specific tasks like javac or jar).

Jonik
+2  A: 

I suggest use some IDE like Netbeans , Eclipse , IntelliJ IDEA and focus on your programming (build yor program by on click) .

SjB