How do I make a JAR from a .java file?

I was writing a simple program using a Java application (not application that has projects, but application within a project; .java) that has a single frame. Both of the files are .java so I can't write a manifest needed by the JAR.

The MyApp.java starts like a class with package, imports then public class MyApp and has a main function, but it's still .java file! I'm writing it in JDeveloper 11g if it helps.

Any ideas how to make a JAR from these files?


Solution 1:

Open a command prompt.

Go to the directory where you have your .java files

Create a directory build

Run java compilation from the command line

javac -d ./build *.java

if there are no errors, in the build directory you should have your class tree

move to the build directory and do a

jar cvf YourJar.jar *

For adding manifest check jar command line switches

Solution 2:

Simply with command line:

javac MyApp.java
jar -cf myJar.jar MyApp.class

Sure IDEs avoid using command line terminal

Solution 3:

Ok this is the solution I would have liked to find, instead here I write it:

First create the directory structure corresponding to the package defined for the .java file, if it is my.super.application create the directory "my" and inside it "super" and inside it the .java file "App.java"

then from command line:

   javac -cp /path/to/lib1.jar:/path/to/lib2.jar path/to/my/super/App.java

Notice the above will include multiple libraries, if under windows use "," to separate multiple files otherwise under GNU/Linux use ":" To create a jar file

   jar -cvfe App.jar App my/app/

the above will create the application with its corresponding Manifest indicating the App as the main class.

Including the required libraries inside the jar file is not possible using java or jar command line parameters.

You can instead:

  1. manually extract libraries to the root folder of the jar file
  2. use an IDE such as Netbeans and insert a rule inside post-jar section of nbproject/build-impl.xml to extract the libraries inside the jar. See below.
<target name="-post-jar">
        <!-- Empty placeholder for easier customization. -->
        <!-- You can override this target in the ../build.xml file. -->
  <jar jarfile="${dist.jar}" update="true">  
            <zipfileset src="${dist.jar}" includes="**/*.class" />  
            <zipfileset src="${file.reference.iText-1.0.8.jar}" includes="**/*"/>
      <zipfileset src="${file.reference.itextpdf-3.2.1.jar}" includes="**/*"/>
  </jar>
    </target>

the file.reference names are found inside project.properties file after you added the libraries to the Netbeans IDE.